php将日期格式转换成xx天前的格式

yipeiwu_com5年前PHP代码库

本文实例讲述了php将日期格式转换成xx天前格式的方法。分享给大家供大家参考。具体如下:

这段代码可以把时间格式化成3天前,5秒前,2年前的形式

// convert a date into a string that tells how long ago
// that date was.... eg: 2 days ago, 3 minutes ago.
function ago($d) {
 $c = getdate();
 $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
 $display = array('year', 'month', 'day', 'hour', 'minute', 'second');
 $factor = array(0, 12, 30, 24, 60, 60);
 $d = datetoarr($d);
 for ($w = 0; $w < 6; $w++) {
 if ($w > 0) {
  $c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
  $d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
 }
 if ($c[$p[$w]] - $d[$p[$w]] > 1) { 
  return ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
 }
 }
 return '';
}
// you can replace this if need be. 
// This converts my dates returned from a mysql date string 
// into an array object similar to that returned by getdate().
function datetoarr($d) {
 preg_match("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2})([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/",$d,$matches);
 return array( 
 'seconds' => $matches[10], 
 'minutes' => $matches[8], 
 'hours' => $matches[6], 
 'mday' => $matches[5], 
 'mon' => $matches[3], 
 'year' => $matches[1], 
 );
}

希望本文所述对大家的php程序设计有所帮助。

相关文章

详解PHP实现异步调用的4种方法

浏览器和服务器之间是通过 HTTP 协议进行连接通讯的。这是一种基于请求和响应模型的协议。浏览器通过 URL 向服务器发起请求,Web 服务器接收到请求,执行一段程序,然后做出响应,发送...

PHP压缩html网页代码(清除空格,换行符,制表符,注释标记)

PHP压缩html网页代码 (清除空格,换行符,制表符,注释标记)。 有个不错的方法就是压缩HTML,压缩html 其实就是:清除换行符,清除制表符,去掉注释标记 。它所起到的作用不可小...

PHP生成和获取XML格式数据的方法

本文实例讲述了PHP生成和获取XML格式数据的方法。分享给大家供大家参考,具体如下: 在做数据接口时,我们通常要获取第三方数据接口或者给第三方提供数据接口,而这些数据格式通常是以XML或...

根据中文裁减字符串函数的php代码

复制代码 代码如下: define(CHARSET, 'UTF-8'); // 系统默认编码 /** * 根据中文裁减字符串 * @param $string - 字符串 * @para...

php中获取关键词及所属来源搜索引擎名称的代码

复制代码 代码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/s...