试图获得两个日期之间的小时差异

时间:2016-03-20 15:58:20

标签: php

我试图在php中获取当前日期和另一个日期之间的时差,但我得到了错误的结果。 到目前为止,她是我的代码:

function hoursDifference($date)
{
   return round((time()- strtotime($date))/3600);
}

输入日期为:2016-03-20 03:55:51但当前时间使用的是24小时格式,因此H为15而不是3,该函数返回正确的12小时时差。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

12小时日期而不是24小时日期使用小写' h'。 您还应该看一下像{fusion3k提到的DateTime::diff

This link还应该帮助您在$ date上使用哪些参数。

答案 1 :(得分:0)

试试这个

 function hoursDifference($date)
 {
  return round(strtotime(date("Y-m-d h:i:s")) - strtotime($date))/3600);
 }

答案 2 :(得分:0)

使用DateTime对象: http://php.net/manual/de/class.datetime.php

echo hoursDifference("2016-03-20 12:13:12");

function hoursDifference($date)
{
    $d = new DateTime($date);
    $now = new DateTime();   
    $iv = $now->diff($d);
    return $iv->h;
}
相关问题