2017-01-26 5 views
0

timeAgoタイムスタンプから返すこのPHP関数があります。 タイムスタンプがNOW よりも大きい場合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'; 
} 

さて、それは "47年前" を返します。 タイムスタンプがNOW よりも大きければ、それは "3日間で、5時間、16分" を返すようにする方法

ありがとうございました。

+1

タイムスタンプの差が<0よりもNOWより大きい場合。 –

答えて

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

関連する問題