2017-01-26 46 views
0

我有这个PHP函数返回timeAgo时间戳PHP timeAgo返回在X日期如果时间戳是未来

function time_ago($time) { 
    $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'); 
    $lengths = array('60', '60', '24', '7', '4.35', '12', '10'); 
    $now = time(); 
    $difference  = $now - $time; 
    for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 
     $difference /= $lengths[$j]; 
    } 
    $difference = round($difference); 
    if ($difference != 1) { 
     $periods[$j] .= 's'; 
    } 
    return $difference . ' ' . $periods[$j] . ' ago'; 
} 

现在,如果时间戳大于NOW,则返回 “47年前成立时”。

如何使它返回 “在3天,5小时16分” 如果时间戳大于NOW

谢谢。

+1

如果时间戳比现在比差<0。 –

回答

1
function time_ago($time) { 
    $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'); 
    $lengths = array('60', '60', '24', '7', '4.35', '12', '10'); 
    $now = time(); 
    // if($now > $time) { 
    $difference  = $now - $time; 
    if ($now < $time) { 
      $difference = $time - $now; 
    } 
    for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 
     $difference /= $lengths[$j]; 
    } 
    $difference = round($difference); 
    if ($difference != 1) { 
     $periods[$j] .= 's'; 
    } 
    //if ($now > $time) { 
    $text = $difference . ' ' . $periods[$j] . ' ago'; 
    } elseif ($now < $time) { 
      $text = 'In ' . $difference . ' ' . $periods[$j]; 
    } 

    return $text; 
} 

这可能行得通。虽然我没有看到添加不同时期的循环,只是第一场比赛。即使这样,你可能在比赛结束后忘了打破循环。

编辑:您可能最好使用DateTime :: diff函数,它与“格式”函数混合,为您自动化该过程,更加准确和高效(因为您的循环是不完整的,它只处理最后一个阵列中的迭代)

http://php.net/manual/en/datetime.diff.php

相关问题