12345678910111213141516171819202122function time_since$since
" /> 12345678910111213141516171819202122function time_since$since
" /> 12345678910111213141516171819202122function time_since$since
" />

首页 / 知识

如何在PHP网页中显示” 12分钟前”等内容?

2023-04-12 16:08:00

如何在PHP网页中显示” 12分钟前”等内容?

How to display “12 minutes ago” etc in a PHP webpage?

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


这是相同的php代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
}

该函数以秒为单位输入并输出诸如以下内容的文本:

  • 10秒
  • 1分钟


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
}

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


网页显示状态消息

最新内容

相关内容

热门文章

推荐文章

标签云

猜你喜欢