2010-01-13 68 views

回答

0

PHP不具有一個內置函數來爲你做它,所以你必須通過做手工。該功能將獲得天,小時,分鐘,秒的差異,在格式返回「X天/小時/分/秒」:

<?php 
function GetTimeDiff($timestamp) { 
    $how_log_ago = ''; 
    $seconds = time() - $timestamp; 
    $minutes = (int)($seconds/60); 
    $hours = (int)($minutes/60); 
    $days = (int)($hours/24); 
    if ($days >= 1) { 
     $how_log_ago = $days . ' day' . ($days != 1 ? 's' : ''); 
    } else if ($hours >= 1) { 
     $how_log_ago = $hours . ' hour' . ($hours != 1 ? 's' : ''); 
    } else if ($minutes >= 1) { 
     $how_log_ago = $minutes . ' minute' . ($minutes != 1 ? 's' : ''); 
    } else { 
     $how_log_ago = $seconds . ' second' . ($seconds != 1 ? 's' : ''); 
    } 
    return $how_log_ago; 
?> 
2

如果這是一個網站,你可能會考慮Timeago。否則,該算法非常簡單。喜歡的東西:

$diff = $date - $now; 
if ($diff > 2 * ONE_YEAR) 
    return sprintf("%d years", round($diff/ONE_YEAR)); 
else if ($diff > ONE_YEAR) 
    return "1 year"; 
else if ($diff > 2 * ONE_MONTH) 
    return sprintf("%d months", round($diff/ONE_MONTH)); 
...etc... 
3

試試這個:

function toFriendlyTime($seconds) { 
    $measures = array(
    'day'=>24*60*60, 
    'hour'=>60*60, 
    'minute'=>60, 
    'second'=>1, 
    ); 
    foreach ($measures as $label=>$amount) { 
    if ($seconds >= $amount) { 
     $howMany = floor($seconds/$amount); 
     return $howMany." ".$label.($howMany > 1 ? "s" : ""); 
    } 
    } 
    return "now"; 
} 

正如你所看到的,它也是靈活添加/刪除的時間的措施,你認爲合適。請務必將這些措施從大到小排列。測試:

now 
1 second 
2 seconds 
1 minute 
1 hour 
1 day 

print(       
    toFriendlyTime(0)."\n"   
    .toFriendlyTime(1)."\n"   
    .toFriendlyTime(2)."\n"   
    .toFriendlyTime(60)."\n"   
    .toFriendlyTime(3600)."\n" 
    .toFriendlyTime(24*3600)."\n"            
    ); 

在結果

相關問題