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?
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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With