Strange release of PHP 5.3 with the calculation of the difference in dates in days

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

$currentDate = new DateTime(); // (today 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 PHP shows the difference of 4 days between the dates of January 27, 2012 and April 1, 2012, when there are still many days between these dates.

Am I doing something wrong?

+7
source share
4 answers

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

 $daysBefore = $diff->days; 
+5
source

When creating a DateInterval via DateTime::diff , it fills not only days, but hours, minutes, seconds, months and even years in the properties of a single character. You check a single-character d for several days, and the rest of the days are considered months.

Try looking at the days property, which is actually populated only when using diff .

The behavior here is wildly inconsistent. Check out the DateInterval::format man page for some interesting information on what happens when you create a DateInterval using various means.

+2
source

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

+2
source

4 days, and in a couple of months ...

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

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

0
source

All Articles