Reputation: 45
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?
Upvotes: 3
Views: 170
Reputation: 13549
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);
Upvotes: 1
Reputation: 4187
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;
Upvotes: 3