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程序设计有所帮助。

相关文章

Yii中render和renderPartial的区别

以下由我们在信易网络公司开发项目的时候终结出的一些经验 在进行页面输出渲染的时候。 1.render 输出父模板的内容,将渲染的内容,嵌入父模板。| 2.renderPartial 则不...

PHP5 字符串处理函数大全

addcslashes — 为字符串里面的部分字符添加反斜线转义字符 addslashes — 用指定的方式对字符串里面的字符进行转义 bin2hex — 将二进制数据转换成十六进制表示...

PHP中文件缓存转内存缓存的方法

前言 顾名思义文件缓存转内存缓存就是将存储在文件中的数据转到内存中去,实现磁盘操作转为内存操作,这样可以大大提高数据访问速度,并能实现缓存数据的分布式部署。文件缓存与内存缓存的介绍请参考...

关于php 高并发解决的一点思路

我的思路如下(伪代码): sql1:查询商品库存 if(库存数量 > 0) { //生成订单... sql2:同时库存-1 } 当没有并发时,上面的流程看起来是再正常不过了...

PHP预定义超全局数组变量小结

本文实例讲述了PHP预定义超全局数组变量。分享给大家供大家参考,具体如下: 1.PHP 预定义的超全局变量数组 特性: a.特殊的数组,操作方式没有区别 b.不用声明,php脚本中默认存...