How do I find the hour difference between two date

2020-01-24 07:31发布

I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.

9条回答
太酷不给撩
2楼-- · 2020-01-24 08:18

As an addition to accepted answer I would like to remind that \DateTime::diff is available!

$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);

/**
 * @var \DateInterval $diff
 */
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise

\DateInterval documentation.

查看更多
放我归山
3楼-- · 2020-01-24 08:21

You can use DateTime interface also -

$d1= new DateTime("06-08-2015 01:33:26pm"); 
$d2= new DateTime("06-07-2015 10:33:26am");
$interval= $d1->diff($d2);
echo ($interval->days * 24) + $interval->h;
查看更多
\"骚年 ilove
4楼-- · 2020-01-24 08:26

This is because of day time saving. Daylight Saving Time (United States) 2014 began at 2:00 AM on Sunday, March 9.

You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to $date2 = "2014-03-14 05:49:23";

查看更多
登录 后发表回答