我想查找日期之間的時間間隔,小時功能在時間更改前一小時無法正常工作。我知道有一個答案部分回答了這個問題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) –