如果时间戳是将来的,则在X天内返回PHP timeAgo

如果时间戳是将来的,则在X天内返回PHP timeAgo,php,time,timeago,Php,Time,Timeago,我有一个PHP函数,它从时间戳返回timeAgo 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 =

我有一个PHP函数,它从时间戳返回timeAgo

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';
}
function time\u ago($time){
$periods=数组(“秒”、“分钟”、“小时”、“日”、“周”、“月”、“年”、“十年”);
$length=数组('60','60','24','7','4.35','12','10');
$now=时间();
$difference=$now-$time;
对于($j=0;$difference>=$length[$j]&&$j
现在,如果时间戳大于现在,它将返回“47年前

如果时间戳大于现在,如何使其在3天5小时16分钟内返回“

谢谢。

功能时间(时间){
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;
}
$periods=数组(“秒”、“分钟”、“小时”、“日”、“周”、“月”、“年”、“十年”); $length=数组('60','60','24','7','4.35','12','10'); $now=时间(); //如果($now>$time){ $difference=$now-$time; 如果($now<$time){ $difference=$time-$now; } 对于($j=0;$difference>=$length[$j]&&$j$time){ $text=$difference.'.$periods[$j].'ago'; }elseif($现在<$时间){ $text='In.$difference.'.$periods[$j]; } 返回$text; }
这可能行得通。虽然我看不到添加不同句点的循环,但只看到第一个匹配。即使如此,在匹配后您可能忘记了打破循环

编辑:您最好使用DateTime::diff函数,该函数与“format”函数混合使用,可以更准确、更高效地自动化此过程(因为循环不完整,只处理数组中的最后一次迭代)


如果时间戳大于现在,则差值小于0。