Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange PHP 5.3 issue with date diff calculating difference in days

I am experiencing a rather strange problem using PHP 5.3's date diff function to calculate the difference in days between two dates. Below is my code:

$currentDate = new DateTime(); // (today's date is 2012-1-27)
$startDate = new DateTime('2012-04-01');

$diff = $startDate->diff($currentDate);

$daysBefore = $diff->d;

echo $daysBefore; 

The above code displays 4 as the value of the $daysBefore variable.

Why is PHP displaying a difference of 4 days between the dates 27th Jan 2012 and 1st April 2012, when clearly there are many more days between these dates.

Am I doing something wrong?

like image 862
Bug Magnet Avatar asked Jan 27 '12 14:01

Bug Magnet


3 Answers

DateInterval::$d is the days part of the interval, not the total number of days of the difference. For that, you want DateInterval::$days, so:

$daysBefore = $diff->days;
like image 154
FtDRbwLXw6 Avatar answered Sep 28 '22 11:09

FtDRbwLXw6


When creating a DateInterval through the DateTime::diff method, it populates not just days, but hours, minutes, seconds, months and even years in the single character properties. You're checking single-character d for days, which will be the days left over once years and months are calculated.

Try looking at the days property, which only actually gets populated when you use diff.

Behavior here is wildly inconsistent. Check out the DateInterval::format manual page for some interesting information about what happens when you create a DateInterval through various means.

like image 31
Charles Avatar answered Sep 28 '22 12:09

Charles


The d property is the number of days as in "3 months, 4 days". If you want the total number of days, use the days property.

like image 27
deceze Avatar answered Sep 28 '22 11:09

deceze