function RelativeTime($timestamp) {
$difference = time() - $timestamp;
$periods = array(
"sec", "min", "hour", "day", "week", "month", "years", "decade"
);
$lengths = array("60", "60", "24", "7", "4.35", "12", "10");
if ($difference > 0) { // this was in the past
$ending = "ago";
} else { // this was in the future
$difference = -$difference;
$ending = "to go";
}
for ($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if ($difference != 1) $periods[$j] .= "s";
$text = "$difference $periods[$j] $ending";
return $text;
}
我在interwebs上找到了上面的PHP函數。它似乎工作得很好,除了它在未來的日期上有問題。PHP函數來計算相對時間(人類可讀/ Facebook風格)
例如,我得到循環PHP錯誤
除以零
爲$difference /= $lengths[$j];
的日期是2033年中
任何想法如何解決呢?該陣列已經佔了幾十年,所以我希望2033年會導致類似「二十年後」的事情。
參考問題:[計算相對時間](http://stackoverflow.com/q/11/367456); [PHP:從時間戳生成相對日期/時間](http://stackoverflow.com/q/2690504/367456); [PHP庫生成用戶友好的相對時間戳](http://stackoverflow.com/q/10171203/367456) – hakre