php 如何在PHP中找到两个日期之间的小时差?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3763476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the hour difference between two dates in PHP?
提问by mike
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.
我有两个日期,格式为“Ymd H:i:s”。我需要比较这两个日期并找出小时差。
回答by Aillyn
You can convert them to timestamps and go from there:
您可以将它们转换为时间戳并从那里开始:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round()
to avoid having a lot of decimal places.
除以 3600 是因为一小时有 3600 秒,round()
用于避免小数点过多。
回答by Sougata Bose
回答by Philippe Gerber
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
回答by Paul T. Rawkeen
As an addition to accepted answer I would like to remind that \DateTime::diff
is available!
作为对已接受答案的补充,我想提醒一下,这\DateTime::diff
是可用的!
$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.
回答by ANF
$date1 = date_create('2016-12-12 09:00:00');
$date2 = date_create('2016-12-12 11:00:00');
$diff = date_diff($date1,$date2);
$hour = $diff->h;
回答by Govinda Yadav
You can try this:
你可以试试这个:
$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
回答by eedue
This is because of day time saving. Daylight Saving Time (United States) 2014 began at 2:00 AM on Sunday, March 9.
这是因为节省了白天时间。2014 年夏令时(美国)于 3 月 9 日星期日凌晨 2:00 开始。
You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to $date2 = "2014-03-14 05:49:23";
您在 $date1 = "2014-03-07 05:49:23" 到 $date2 = "2014-03-14 05:49:23" 期间损失一小时;
回答by Colin Hebert
You can use strtotime()
to parse your strings and do the difference between the two of them.
您可以使用strtotime()
来解析您的字符串并在它们之间进行区分。
Resources :
资源 :
回答by Michael
The problem is that using these values the result is 167 and it should be 168:
问题是使用这些值的结果是 167,它应该是 168:
$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;