Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date_diff function returns wrong result

Tags:

date

php

datediff

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?

like image 493
Shijin TR Avatar asked Jul 05 '26 07:07

Shijin TR


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

like image 147
jspit Avatar answered Jul 07 '26 23:07

jspit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!