1

I am struggeling with some basic date-formatting and echo the right number for "Days Left". This is the code:

date_default_timezone_set('Europe/Oslo');
$dateNow = date('d/m/Y', time());
$dateStart = date('d/m/Y', strtotime('01/08/2014'));
$dateFinished = date('d-m-Y', $dateStart + strtotime("+62 days"));
$daysLeft = intval($dateFinished-$dateNow);

echo($dateNow. "<br>");
echo($dateStart. "<br>");
echo($daysLeft. "<br>");

This is the echo: 07/07/2014 01/08/2014 -6

It seems like dateStart is interped as a wrong format. I have tried with both - and /, but nothing better.

What have i done wrong? Just the math or is it the logic?

1
  • var_dump($dateStart + strtotime("+62 days")); --- never assume, always check. Commented Jul 7, 2014 at 11:44

3 Answers 3

2

I recommend to use OOP (Object-oriented) in this case. It is easier to write and easier to understand.

Just made a simple and short script:

<?php
date_default_timezone_set('Europe/Oslo');
$dateNow = new DateTime('now');
$dateStart = new DateTime('2014-08-01');
$dateFinished = new DateTime($dateStart->format('Y-m-d'));
$dateFinished->add(new DateInterval('P62D'));
$daysLeft = $dateFinished->diff($dateNow);

echo($dateNow->format('d/m/Y'). "<br>");
echo($dateStart->format('d/m/Y'). "<br>");
echo($daysLeft->format('%d'). "<br>");
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't this modify datestart to? $dateStart->add(new DateInterval('P62D') @Yannici
Of course. Thank you for the hint :P I just edited my answer.
2

$dateStart is a string. You need to do:

$dateStart = date('d/m/Y', strtotime('01/08/2014'));
$dateFinished = date('d-m-Y', strtotime("+62 days", strtotime('01/08/2014')));

For more sophisticated date calculations consider DateTime().

Comments

1

If your PHP is 5.3+, than you can use DateTime class and calculate difference between dates:

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);

echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

OR

echo "difference " . $interval->days . " days ";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.