Warm tip: This article is reproduced from stackoverflow.com, please click
date datetime php dateinterval

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

发布于 2020-03-31 22:53:01

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
Questioner
marcv
Viewed
97
13.3k 2019-05-23 20:49

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