简体   繁体   中英

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?

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.

4 days, and a couple months...

Use $diff->days for total number of days.

http://www.php.net/manual/en/class.dateinterval.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM