时间戳友好化格式化函数

jerry thinkphp 2015年11月18日 收藏
友好格式化时间戳
在一些微博系统中经常要将时间于现在时间相比显示为多久以前发布的,如显示为:刚刚、5秒前、5小时前、5天前..这种
  1. /**
  2.  *
  3.  +--------------------------------------------------------------------
  4.  * Description 友好显示时间
  5.  +--------------------------------------------------------------------
  6.  * @param int $time 要格式化的时间戳 默认为当前时间
  7.  +--------------------------------------------------------------------
  8.  * @return string $text 格式化后的时间戳
  9.  +--------------------------------------------------------------------
  10.  * @author yijianqing
  11.  +--------------------------------------------------------------------
  12.  */
  13. function mdate($time = NULL) {
  14.     $text = '';
  15.     $time = $time === NULL || $time > time() ? time() : intval($time);
  16.     $t = time() - $time; //时间差 (秒)
  17.     if ($t == 0)
  18.         $text = '刚刚';
  19.     elseif ($t < 60)
  20.         $text = $t . '秒前'; // 一分钟内
  21.     elseif ($t < 60 * 60)
  22.         $text = floor($t / 60) . '分钟前'; //一小时内
  23.     elseif ($t < 60 * 60 * 24)
  24.         $text = floor($t / (60 * 60)) . '小时前'; // 一天内
  25.     elseif ($t < 60 * 60 * 24 * 3)
  26.         $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
  27.     elseif ($t < 60 * 60 * 24 * 30)
  28.         $text = date('m月d日 H:i', $time); //一个月内
  29.     elseif ($t < 60 * 60 * 24 * 365)
  30.         $text = date('m月d日', $time); //一年内
  31.     else
  32.         $text = date('Y年m月d日', $time); //一年以前
  33.     return $text;
  34. }
使用此函数,我们只需在前台用
  1. {$vo.time|mdate}
实现时间友好化显示了