谁能告诉我如何在网页中显示“12 秒前”或“5 分钟前”等状态消息?
Niyaz
问问题
30692 次
3 回答
72
这是相同的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;
}
该函数将秒数作为输入并输出文本,例如:
- 10 秒
- 1分钟
ETC
于 2008-08-20T20:02:48.933 回答
16
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;
}
于 2013-04-27T04:11:02.270 回答
6
PHP\DateTime::diff
返回一个对象,您可以在该对象上通过公共属性\DateInterval
获取分钟。i
于 2014-05-05T15:05:42.357 回答