计算并显示日期为“之前”,“分钟前”,“小时前”等 [英] calculating and showing a date as 'secs ago', 'mins ago', 'hours ago' etc
问题描述
我有一个小的自定义博客类型的东西,并希望在评论旁边显示日期。
我想以格式的:
发布23秒前
发布43分钟前
发布1小时前
发布1天之前
发布2周前
...
可能不会比这更长,因为没有显示超过一个月的文章。
我可以在MySQL中存储日期时间或时间戳格式的实际日期...
任何人都知道现有的功能PHP可以用来做这个吗?我还没有找到适合的东西。
您可以使用以下函数将其称为 format_interval(time() - $ saved_timestamp)
,其中 $ saved_timestamp
是您感兴趣的事件的时间戳。
function format_interval($ interval,$ granularity = 2){
$ units = array('1 year | @count years'=> 31536000,'1 week | @计数星期'=> 604800,'1天| @count天'=> 86400,'1小时| @count hours'=> 3600,'1分钟| @count最小'=> 60,'1秒| @count sec'=> 1);
$ output ='';
foreach($ units as $ key => $ value){
$ key = explode('|',$ key);
if($ interval> = $ value){
$ floor = floor($ interval / $ value);
$ output。=($ output?'':'')。 ($ floor == 1?$ key [0]:str_replace('@ count',$ floor,$ key [1]));
$ interval%= $ value;
$ granularity--;
}
if($ granularity == 0){
break;
}
}
返回$输出? $ output:'0 sec';
}
I've got a small custom made blog type thing and want to display the date posted next to comments.
I'd like to do it in the format of:
posted 23 secs ago
posted 43mins ago
posted 1hr ago
posted 1day ago
posted 2 weeks ago
...
probably won't get much longer than that because articles older than a month aren't shown.
I can stored the actual date in datetime or timestamp format in MySQL...
Anyone know of a function that's existing for PHP which I could use to do this? I haven't really found anything that suits yet.
You can use the following function and call it as format_interval(time() - $saved_timestamp)
, where $saved_timestamp
is the timestamp of the "event" you are interested in.
function format_interval($interval, $granularity = 2) {
$units = array('1 year|@count years' => 31536000, '1 week|@count weeks' => 604800, '1 day|@count days' => 86400, '1 hour|@count hours' => 3600, '1 min|@count min' => 60, '1 sec|@count sec' => 1);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($interval >= $value) {
$floor = floor($interval / $value);
$output .= ($output ? ' ' : '') . ($floor == 1 ? $key[0] : str_replace('@count', $floor, $key[1]));
$interval %= $value;
$granularity--;
}
if ($granularity == 0) {
break;
}
}
return $output ? $output : '0 sec';
}
这篇关于计算并显示日期为“之前”,“分钟前”,“小时前”等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!