2011-03-17 81 views
2

我想創建一個函數比較一個日期和當前時間,並返回一個很好格式化的字符串。
我已經寫了一些代碼在匆忙,它的工作原理,但我試圖找到一個更有效的方式來做到這一點。這裏是我的代碼:功能,格式化時差

function _formatDate($dateStr) 
    { 
    $timestr = ""; 
    $t= time() - strtotime($dateStr); 
    if($t < 60) { 
     $timestr = "{$t} seconds ago"; 
    } 
    elseif ($t <120) { 
     $timestr = "about a minute ago"; 
    } 
    elseif ($t < 3600) { 
     $minute = floor($t/60); 
     $timestr = "{$minute} minutes ago"; 
    } 
    elseif ($t < 7200) { 
     $timestr = " about an hour ago"; 
    } 
    elseif ($t < 86400) { 
     $hour = floor($t/3600); 
     $timestr = "{$hour} hours ago"; 
    } 
    elseif ($t < 172800) { 
     $timestr = "a day ago"; 
    } 
    elseif ($t < 2592000) { 
     $day = floor($t/86400); 
     $timestr = "{$day} days ago"; 
    } 
    elseif ($t < 5184000){ 
     $timestr = "about a month ago"; 
    } 
    else { 
     $month = floor($t/2592000); 
     $timestr = "{$month} months ago"; 
    } 
    return $timestr; 
} 
+0

我試圖通過日期作爲參數,並讓它自動返回格式化前:22分鐘前,或3天前 – Ibu 2011-03-17 19:07:18

+1

那麼你的代碼有什麼問題?似乎做你在問什麼。如果這是一個網頁,輸出日期/時間戳,然後使用JS(和TimeAgo等庫)來更新值可能是有益的。 – Rudu 2011-03-17 19:12:17

+0

我想知道是否有更有效的方法來做到這一點,沒有太多if else語句。 – Ibu 2011-03-17 19:16:57

回答

4

一些代碼,我使用,它從來沒有失敗,只是把Unix時間戳,如果你使用的功能的第二個參數可以是「爲」條件

echo timeDiffrence('1300392875'); 

function timeDiffrence($from, $to = null){ 
    $to = (($to === null) ? (time()) : ($to)); 
    $to = ((is_int($to)) ? ($to) : (strtotime($to))); 
    $from = ((is_int($from)) ? ($from) : (strtotime($from))); 
    $units = array 
    (
    "y" => 29030400, // seconds in a year (12 months) 
    "month" => 2419200, // seconds in a month (4 weeks) 
    "w" => 604800, // seconds in a week (7 days) 
    "d" => 86400, // seconds in a day (24 hours) 
    "h" => 3600,  // seconds in an hour (60 minutes) 
    "m" => 60,  // seconds in a minute (60 seconds) 
    "s" => 1   // 1 second 
    ); 
    $diff = abs($from - $to); 
    $suffix = (($from > $to) ? ("from now") : ("ago")); 
    foreach($units as $unit => $mult) 
    if($diff >= $mult) 
    { 
     //$and = (($mult != 1) ? ("") : ("and ")); 
     $output .= "".$and.intval($diff/$mult)."".$unit.((intval($diff/$mult) == 1) ? ("") : ("")); 
     $diff -= intval($diff/$mult) * $mult; 
    } 
    $output .= " ".$suffix; 
    $output = substr($output, strlen("")); 
    if($output =='go' || $output ==' ago'){$output = 'A few secs ago';} 
    return $output; 
} 
1

我建議在javascript中使用它。你可以使用jQuery的TimeAgo插件。關於這一點很酷的是它將在客戶端實時更新而不需要刷新任何頁面。這是使用簡單,符合您的要求。