Search code examples
phpdatedatediff

PHP date_diff function returns wrong result


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?


Solution

  • 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.