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;
}
我在互联网上找到了上面的 PHP 函数。它似乎工作得很好,除了它在遥远的未来日期方面存在问题。
例如,我得到循环 PHP 错误
被零除
$difference /= $lengths[$j];
当日期是 2033 年时。
任何想法如何解决这个问题?该阵列已经占了几十年,所以我希望 2033 年会产生类似“未来 2 年”的结果。