关于WordPress的时间显示函数human_time_diff
网页上的时间显示格式大致可分为两种:绝对日期时间和相对日期时间
绝对日期时间即是传统的显示时间,如:2010-08-10 14:25、Aug 10 2010、2010年8月10日等;
另一种相对日期时间就是想twitter、Digg上的那种时间显示格式:2 days ago、5 mins、15小时前等。
这两种格式的实现方法大致如下:
-
绝对日期时间:传统时间格式
传统时间显示格式的方法就是php的the_time参数,如
<?php the_time('Y-m-d H:i:s') ?>会显示为形如:2010-08-10 14:50:22 -
相对日期时间:Twitter、Digg式的时间显示形式-time ago
- 关于Twitter、Digg形式的时间显示格式有两种形式:
-
实现方法一:自定义函数
函数如下:
function timeAgo($timestamp, $granularity=2, $format='Y-m-d H:i:s'){
$difference = time() - $timestamp;
if($difference < 0) return '0 seconds ago';
elseif($difference < 864000){ $periods = array('week' => 604800,'day' => 86400,'hr' => 3600,'min' => 60,'sec' => 1);
$output = '';
foreach($periods as $key => $value){
if($difference >= $value){
$time = round($difference / $value);
$difference %= $value;
$output .= ($output ? ' ' : '').$time.' ';
$output .= (($time > 1 && $key == 'day') ? $key.'s' : $key);
$granularity--;
}
if($granularity == 0) break;
}
return ($output ? $output : '0 seconds').' ago';
}
else return date($format, $timestamp);
}
输出代码:
$time = timeAgo($dateRef);这个方法来自
-
实现方法二:WordPress human_time_diff函数
对于WordPress用户来说,不要这么麻烦了,因为WordPress已经有human_time_diff参数了,格式如下:
<?php human_time_diff( $from, $to ) ?>
$from:时间戳起始时间,默认为none
$to:时间戳终止时间,默认为''
如将WordPress评论时间显示为“2 days ago”格式,代码如下:
<?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; ?>
注意:使用的时候请将“get_comment_time”改成你需要的时间函数
-
?
额。。。。。已经有了。。
@QiQiBoY
感觉这个很好玩,有个性吧
用了你的方法,十分感谢!
我在其他地方调用了这个之后 ;总是显示15016 天 ago,怎么回事?