计算相对时间的PHP函数(人类可读/ Facebook风格)


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错误

除以0

当日期为2033年时,

$difference /= $lengths[$j];

有什么办法解决这个问题吗?数组已经占了几十年,所以我希望2033年的结果是"20年"。

问题是第二个数组$lengths包含7个元素,因此在执行循环的最后一次迭代时(除以10后-几十年)$j = 7, $lengths[7]是未定义的,因此转换为0,因此测试$difference >= $lengths[$j]返回true。然后代码进入一个无限循环。为了克服这个问题,只需在$lengths数组中再添加一个元素,比如"100",这样for循环就会在处理了几十年后终止。请注意,如果日期在2038年1月19日之前,则可以用UNIX时间戳表示。因此,您不能计算超过4个十进制的日期,因此100足以脱离循环。

最新更新