Strange PHP 5.3 issue with date diff calculating difference in days

断了今生、忘了曾经 提交于 2019-12-06 23:59:34

问题


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?


回答1:


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;



回答2:


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.




回答3:


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:


4 days, and a couple months...

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

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



来源:https://stackoverflow.com/questions/9034674/strange-php-5-3-issue-with-date-diff-calculating-difference-in-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!