php 将unix时间戳输出类似20秒前,1天前等的格式

将unix时间戳输出为类似于 20秒前,1天前,3个月前这样的格式,PHP将unix时间戳替换成易于阅读的格式,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:

/**
 * unix时间戳输出类似20秒前,1天前等的格式
 *
 * @param 
 * @arrange (512.笔记) jb51.cc
 **/
function user_friendly_date($timestamp,$echo = false,$dateFormat = 'm/d/Y H:i:s')
{
 $ufdate = '';
 $now = time();
 $elapsed = $now - $timestamp;
 if($elapsed <= 0) $ufdate = 'Now';
 else if($elapsed == 1) $ufdate = "1 Second ago";
 else if($elapsed < 60) $ufdate = "{$elapsed} Seconds ago";
 else if($elapsed < 3600) //One hour in seconds
 {
  $mins = floor($elapsed/60);
  $secs = $elapsed%60;
  $disp = min(($secs <= 30 ? $mins : $mins + 1),59);
  $ufdate = "{$disp} Minute" . ($disp == 1 ? '' : 's') ." ago";
 }
 else if($elapsed < 86400) //One day in seconds
 {
  $hours = floor($elapsed/3600);
  $mins = floor(($elapsed%3600)/60);
  $disp = min(($mins <= 30 ? $hours : $hours + 1),23);
  $ufdate = "{$disp} Hour" . ($disp == 1 ? '' : 's') ." ago";
 }
 else if($elapsed < 604800) //One week in seconds
 {
  $days = floor($elapsed/86400);
  $hours = floor(($elapsed%86400)/3600);
  $disp = min(($hours <= 12 ? $days : $days + 1),6);
  $ufdate = "{$disp} Day" . ($disp == 1 ? '' : 's') ." ago";
 }
 else $ufdate = date($dateFormat,$timestamp);
 if($echo) echo $ufdate;
 return $ufdate;
}
 
//Usage
$now = time();
$tenSecsAgo = $now - 10;
$oneMinuteAgo = $now - 60;
$thirtyNineMinsAgo = $now - (39 * 60); //minutes * seconds
$elevenHoursAgo = $now - (11 * 60 * 60); //hours * minutes * seconds
$twoDaysAgo = $now - (2 * 24 * 60 * 60); //days * hours * minutes * seconds
 
echo "<p>\n";
echo user_friendly_date($tenSecsAgo)," <br>\n";
echo user_friendly_date($oneMinuteAgo)," <br>\n";
echo user_friendly_date($thirtyNineMinsAgo)," <br>\n";
echo user_friendly_date($elevenHoursAgo)," <br>\n";
echo user_friendly_date($twoDaysAgo)," <br>\n";
echo "</p>";



/***   来自编程之家 jb51.cc(jb51.cc)   ***/

相关文章

Hessian开源的远程通讯,采用二进制 RPC的协议,基于 HTTP 传输。可以实现PHP调用Java,Python,C#等多语...
初识Mongodb的一些总结,在Mac Os X下真实搭建mongodb环境,以及分享个Mongodb管理工具,学习期间一些总结...
边看边操作,这样才能记得牢,实践是检验真理的唯一标准.光看不练假把式,光练不看傻把式,边看边练真把式....
在php中,结果输出一共有两种方式:echo和print,下面将对两种方式做一个比较。 echo与print的区别: (...
在安装好wampServer后,一直没有使用phpMyAdmin,今天用了一下,phpMyAdmin显示错误:The mbstring exte...
变量是用于存储数据的容器,与代数相似,可以给变量赋予某个确定的值(例如:$x=3)或者是赋予其它的变...