如何在PHP网页上显示"12分钟前"等?

Niy*_*yaz 28 php

任何人都可以告诉我如何在网页中显示"12秒前"或"5分钟前"等状态消息?

Niy*_*yaz 67

这是相同的PHP代码:

function time_since($since) {
    $chunks = array(
        array(60 * 60 * 24 * 365 , 'year'),
        array(60 * 60 * 24 * 30 , 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24 , 'day'),
        array(60 * 60 , 'hour'),
        array(60 , 'minute'),
        array(1 , 'second')
    );

    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
    return $print;
}
Run Code Online (Sandbox Code Playgroud)

该函数将输入和输出文本的秒数视为:

  • 10秒
  • 1分钟

等等

  • 由于我很好奇,用评估的产品替换乘法序列的速度提高了约1.2%. (10认同)
  • 无论我改变日期和时间,它只显示"33分钟" (5认同)
  • @ErikEdgren我有同样的问题,因为我发送日期而不是秒.试试这个:`time_since(time() - strtotime($ datetime))` (5认同)

Dip*_*esh 14

function timeAgo($timestamp){
    $datetime1=new DateTime("now");
    $datetime2=date_create($timestamp);
    $diff=date_diff($datetime1, $datetime2);
    $timemsg='';
    if($diff->y > 0){
        $timemsg = $diff->y .' year'. ($diff->y > 1?"'s":'');

    }
    else if($diff->m > 0){
     $timemsg = $diff->m . ' month'. ($diff->m > 1?"'s":'');
    }
    else if($diff->d > 0){
     $timemsg = $diff->d .' day'. ($diff->d > 1?"'s":'');
    }
    else if($diff->h > 0){
     $timemsg = $diff->h .' hour'.($diff->h > 1 ? "'s":'');
    }
    else if($diff->i > 0){
     $timemsg = $diff->i .' minute'. ($diff->i > 1?"'s":'');
    }
    else if($diff->s > 0){
     $timemsg = $diff->s .' second'. ($diff->s > 1?"'s":'');
    }

$timemsg = $timemsg.' ago';
return $timemsg;
}
Run Code Online (Sandbox Code Playgroud)

  • 我使用了这个的修改版本,我用 $datetime2 = new DateTime(); 替换了 date_create 行。$datetime2-&gt;setTimestamp($timestamp); 并删除了 s 字符串之前的所有撇号 (2认同)

Seb*_*ers 5

PHP的\DateTime::diff返回一个\DateInterval对象,您可以在该对象上通过public i属性获取会议记录。