简体   繁体   English

PHP <5.3 =>两个日期之间的小时差

[英]PHP < 5.3 => Difference in hours between two dates

In a current project I have hit a wall because I need to compare two dates and find the difference between the dates (in hours), this would be easy if the server was >= 5.3, can someone help me? 在当前项目中,我遇到了麻烦,因为我需要比较两个日期并找出日期之间的差异(以小时为单位),如果服务器> = 5.3,这会很容易,有人可以帮助我吗?

I have the difference in timestamp 我在时间戳上有区别

$diff = abs(strtotime($date1)-strtotime($date2)

but I don't know what to do next... 但我不知道下一步该怎么做...

Thank you. 谢谢。

In your code $diff is the difference in seconds. 在您的代码$diff是秒的差异。 You can convert the seconds to hours like this: 您可以像这样将秒转换为小时:

$hours = floor($diff / (60 * 60));

Edit: To get minutes and seconds: 编辑:要获取分钟和秒:

$minutes = floor(($diff - $hours * 60 * 60) / 60);
$seconds = floor($diff - $hours * 60 * 60 - $minutes * 60);

尝试这个

echo round((strtotime($date1) - strtotime($date2))/(60*60));

In your code $diff is in seconds. 在您的代码中$ diff以秒为单位。 There are 3600 seconds in an hour, so: 一个小时中有3600秒,因此:

$date1 = "2014-07-15";
$date2 = "2014-07-17";

$diff_seconds = abs(strtotime($date1)-strtotime($date2));
$diff_hours = $diff_seconds/3600;

echo $diff_seconds.' '.$diff_hours;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM