PHP date_diff function returns wrong result

Viewed 758

I was trying to find the number of months between two dates using date_diff() in PHP. As we all know the number of months between 2019-03-01 and 2020-01-31 is 11 months, but the following code return 10 months.

$date1=date_create("2019-03-01");
$date2=date_create("2020-01-31");
$diff=date_diff($date1,$date2);
echo $diff->format("%m months");

Output

10 months

Why this code return 1 month less?

2 Answers

If you need the difference in months from the beginning of the first day to the end of the last day at midnight, you can also set the end date to midnight (24h !) or add a day.

<?php
$dateStart = date_create("2019-03-01");
$dateEnd = date_create("2020-01-31");

//set Time to midnight or add a day
$dateEnd->setTime(24,0,0);

$diff = date_diff($dateStart,$dateEnd);
echo $diff->format("%m months");
//11 months

try self.

The difference is 10 months and 30 days, which is what date_diff() returns:

object(DateInterval)#3 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(10)
  ["d"]=>
  int(30)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(336)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

ETA as @showdev commented above.

Related