前段时间大家都热衷于在wordpress上显示“XX小时,XX分钟前”类似的时间显示方式。
我在开发社交媒体连接插件的最新微博功能时,也想将微博的时间显示与新浪微博的显示方式一致。具体的要求如下:
一分钟之内显示“刚刚”;大于一分钟小于一个小时显示“XX分钟之前”;大于一个小时但在当天之内(小于当天24点),显示“今天 XX:XX”,今天之前,但是在今年之内的显示“XX月XX日,XX:XX”,今年以前的显示“XXXXXX月XX日,XX:XX”。
由于要考虑到不同地区的时差问题,我的实现方式如下:
/** 微博时间格式化显示
* @param $timestamp,标准时间戳
*/
function smc_time_since($timestamp) {
$since = abs(time()-$timestamp);
$gmt_offset = get_option('gmt_offset') * 3600;//获取wordpress的时区偏移值
$timestamp += $gmt_offset; $current_time = mktime() + $gmt_offset;
if(floor($since/3600)){
if(gmdate('Y-m-d',$timestamp) == gmdate('Y-m-d',$current_time)){
$output = '今天 ';
$output.= gmdate('H:i',$timestamp);
}else{
if(gmdate('Y',$timestamp) == gmdate('Y',$current_time)){
$output = gmdate('m月d日 H:i',$timestamp);
}else{
$output = gmdate('Y年m月d日 H:i',$timestamp);
}
}
}else{
if(($output=floor($since/60))){
$output = $output.'分钟前';
}else $output = '刚刚';
}
return $output;
}
另外我后来在新浪微博发布的开源Xweibo的源码中找到了其所用的方法,只是我觉得一点繁琐,有兴趣的同学可以下载Xweibo的源码,然后在xweibo_upload\application\function\format_time.func.php的12行可以看到新浪微博的实现方式。个人觉得其有一点繁琐了,也许我没看懂他的思路。有兴趣各位可以参考下。
效果见我博客右边栏的微博显示部分。你也可以下载社交媒体连接插件,在你的博客上显示最新微博。
