Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the difference between two DateTime objects does not work?

I've got a problem with my "DateTime difference code":

$timeStart = new DateTime('2015-11-28');
$timeEnd = new DateTime('2016-11-28');
$interval = $timeEnd->diff($timeStart);
$result = $interval->format('%d');

echo $result." day(s)";

When I visualize $result, PHP show me 0. But between those two dates there are more days than 0 day...

php does not calculate the difference between two dates that are not in the same year?

like image 689
Syxmoke Avatar asked Jul 01 '26 14:07

Syxmoke


2 Answers

Because there are 0 days difference. There is however a 1 year difference. If you changed %d to %y you'd get 1. So there's a difference of 1 year, 0 months and 0 days.

What you can use instead is the days property on DateInterval, as such:

$result = $interval->days;

like image 70
Jonnix Avatar answered Jul 03 '26 04:07

Jonnix


Okay, I'm aware the answer was given already. But below is just a bit explanation.

In fact, DateInterval::format() does makes sense when you have a fixed amount of time (in years, months, days, hours), like this:

$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

That isn't your case!
where you have a relative time (2016-11-28 related to 2015-11-28) at all. In this specific case you want the days amount past since 28-11-2015.
That's why DateInterval::days (DateTime::diff() returns a DateInterval object) makes sense:

$start = new DateTime('2015-11-28');
$end   = new DateTime('2016-12-28');

var_dump($end->diff($start)->days);
like image 44
felipsmartins Avatar answered Jul 03 '26 04:07

felipsmartins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!