7

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?

Bug Magnet
  • 2,668
  • 5
  • 29
  • 28

4 Answers4

5

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;
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
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.

Charles
  • 50,943
  • 13
  • 104
  • 142
2

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

4 days, and a couple months...

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

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

Brad
  • 159,648
  • 54
  • 349
  • 530