2011-11-02 59 views
2
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年會導致類似「二十年後」的事情。

+0

參考問題:[計算相對時間](http://stackoverflow.com/q/11/367456); [PHP:從時間戳生成相對日期/時間](http://stackoverflow.com/q/2690504/367456); [PHP庫生成用戶友好的相對時間戳](http://stackoverflow.com/q/10171203/367456) – hakre

回答

2

的問題是,所述第二陣列$lengths包含7個元素,從而執行循環的最後一次迭代時(由10 deviding後 - 爲對數十年)$j = 7$lengths[7]是未定義的,所以轉換爲0,因此,測試$difference >= $lengths[$j]返回true。然後代碼進入無限循環。爲了克服這個問題,只需在$lengths數組中添加一個元素,比如說「100」,這樣for循環在處理了幾十年之後就終止了。請注意,如果日期在2038年1月19日之前,則可以在UNIX時間戳中表示日期。因此,您不能計算超過4次的日期,因此100可以從循環中斷開。

+0

謝謝。這解決了它。 – 0pt1m1z3