0

I'm trying to use date_diff to compare two dates, but it's not even coming close to the right number. To troubleshoot, I'm doing a simple hard-coded test:

$date1              = date_create("2014-03-20");
$date2              = date_create("2017-11-13");
$diff               = date_diff($date1,$date2);     
echo               $diff->format('%r%d');

This outputs "24" for me -- so it's not even in the ballpark. Any ideas what's going wrong here?

Matt
  • 175
  • 1
  • 10
  • With so much attention, I am surprised that no one asked Matt to read the manual, downvoted, and closed this as a mega-duplicate. The regular defenders of SO must be offline. – mickmackusa Jan 16 '18 at 04:06

3 Answers3

8

The $diff outcome contains a DateInterval object. It contains the following:

DateInterval Object
(
    [y] => 3
    [m] => 7
    [d] => 24
    [h] => 0
    [i] => 0
    [s] => 0
    [f] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 1334
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

By echo'ing $diff->d you'll get the day difference. If you'd like to have the total amount of days. Use $diff->days. Just play around with it.

Jordi Kroon
  • 2,607
  • 3
  • 31
  • 55
  • thanks, i wound up playing with it based on your suggestion and @marcell's answer to get $diff->format('%r%a') which will show negative differences as well – Matt Jan 15 '18 at 22:56
4

You are using format codes for dates in PHP, but yet you are having a date interval, that has different format codes.

echo $diff->format('%y-%m-%d');

This will show the correct value.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
2

If you are looking for the total number of days you should use the a format character. See more at php date interval format.

$diff->format('%a');

output:

1334
marcell
  • 1,498
  • 1
  • 10
  • 22