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


Trying to get the difference in hours between two dates

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

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

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

对于 12 小时日期而不是 24 小时日期,请使用小写的"h"。你还应该看看 DateTime::d iff 就像@fusion3k提到的那样。

此链接还可以帮助您确定可以在$date上使用哪些参数。

试试这个

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

使用 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;
}