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 mvc开发模式的感想

使用mvc开发模式是为了什么?? MVC是一个设计模式,它强制性的使应用程序的输入、处理和输出分开。使用MVC应用程序被分成三个核心部件:模型、视图、控制器。它们各自处理自己的任务。 我...

PHP伪静态写法附代码

比如这个网页 //www.jb51.net/soft.php/1,100,8630.html 其实处理的脚本是soft.php 参数为1,100,8630 相当于soft.ph...

PHP 无限分类三种方式 非函数的递归调用!

PHP 无限分类三种方式 非函数的递归调用!

php无限分类大致有三种方式,   1、数据库通过设置父类ID来进行唯一索引,然后使用函数的递归调用实现无限分类;   2、数据库设计通过特定格式进行排列,然后使用mysql查询关键函数...

PHP错误提示的关闭方法详解

最简单的办法就是直接在php程序代码中加入下面代码: 复制代码 代码如下:error_reporting(E_ALL^E_NOTICE^E_WARNING); 可以关闭所有notice...

php 字符转义 注意事项

在php中: * 以单引号为定界符的php字符串,支持两个转义\'和\\ * 以双引号为定界符的php字符串,支持下列转义: \n 换行(LF 或 ASCII 字符 0x0A(10))...