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实现的简单在线计算器功能示例

PHP实现的简单在线计算器功能示例

本文实例讲述了PHP实现的简单在线计算器功能。分享给大家供大家参考,具体如下: <html> <head> <meta http-equiv="cont...

PHP中函数rand和mt_rand的区别比较

PHP函数rand和mt_rand    mt_rand() 比rand() 快四倍      很多老的 libc 的随机数发生器具有一些不确定和未知的特性而且很慢。PHP 的 rand...

sae使用smarty模板的方法

Smarty是非常流行的模板系统,它分离了业务和逻辑、执行速度快,在php网站中有广泛的运用。 不过在部署到sina app engine(sae)上时出现了问题,因为sae作为云计算平...

PHP 编写大型网站问题集

PHP以其易用性得到迅速的推广,但易用并不是说就能用好它,实际上许多程序员用它很容易的立一个个WEB应用系统,但又有多少人仔细的考虑过他们的代码,是否容易维护、是否足够健壮、否效率足够高...

php绘制一条弧线的方法

本文实例讲述了php绘制一条弧线的方法。分享给大家供大家参考。具体如下: 弧线相当于截取了椭圆的一部分。代码如下: 复制代码 代码如下:<?php //1、创建画布 $im...