Get a PHP DateTime difference in days, considering midnight as a day change

marcv picture marcv · Aug 7, 2013 · Viewed 50.3k times · Source

What is the simplest way to get the difference in days between two PHP DateTimes, considering midnight as a day change (just like the DATEDIFF(DAY) SQL function does)?

For example, between today at 13:00 and tomorrow at 12:00, I should get 1 (day), even though the interval is less than 24 hours.

$date1 = new DateTime("2013-08-07 13:00:00");
$date2 = new DateTime("2013-08-08 12:00:00");
echo $date1->diff($date2)->days; // 0

Answer

MajorCaiger picture MajorCaiger · Aug 7, 2013

You could ignore the time portion of the date string

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00")));
$date2 = new DateTime(date('Y-m-d', strtotime("2013-08-08 12:00:00")));
echo $date1->diff($date2)->days; // 1