我想查找日期之间的时间间隔,小时功能在时间更改前一小时无法正常工作。我知道有一个答案部分回答了这个问题here。但它不会按小时来回答。日期之间的时间间隔(包括小时数)php
我有下面的PHP代码:
//helper function to pluralize words
function pluralize($count, $text){
return $count . (($count == 1) ? (" $text") : (" ${text}s"));
}
/**
* Difference of dates
* @param type $date1 DateTime first date
* @param type $date2 DateTime second date
* @return type string year, month, day, hour, minute, second
*/
function timeDiff($date1, $date2){
$string = "";
$interval =$date1->diff($date2);
$suffix = ($interval->invert ? ' ago' : '');
if ($v = $interval->y >= 1) $string .= pluralize($interval->y, 'year'). ', ';
if ($v = $interval->m >= 1) $string .= pluralize($interval->m, 'month'). ', ';
if ($v = $interval->d >= 1) $string .= pluralize($interval->d, 'day'). ', ';
if ($v = $interval->h >= 1) $string .= pluralize(($interval->h), 'hour') . ', ';
if ($v = $interval->i >= 1) $string .= pluralize($interval->i, 'minute'). ', ';
if ($v = $interval->i >= 1) $string .= pluralize($interval->s, 'second'). ' ';
return $string . $suffix;
}
我想下面的测试通过。
$date1 = new DateTime("2014-05-10 20:00:00");
$date2 = new DateTime("2015-11-20 19:45:00");
//This should produce "1 year, 6 months, 9 days, 23 hours, 45 minutes"
//But it does produce "1 year, 6 months, 10 days, 45 minutes"
timeDiff($date1, $date2);
$date3 = new DateTime("2015-11-20 20:00:00");
//This should, and does produce "1 year, 6 months, 10 days"
timeDiff($date1, $date3);
这看起来像@John Conde在评论中指出的version issue。它已在新版本的PHP 5.4.24及更高版本中修复。我如何解决此问题以前版本的PHP?
https://eval.in/473043 –
你是说我的服务器做错了什么?这很有趣。有版本的PHP的一个已知的问题? – Whitecat
[看起来像版本问题](https://3v4l.org/Kp26c) –