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

yipeiwu_com6年前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伪造referer实例代码

这里就直接给出完整的程序吧,具体的应用可以自己修改。 我这里给出的例子是很简单的,其实可以从这个例子中发展出很多的应用。比如隐藏真实的URL地址……嘿嘿,具体的就自己分析去吧 这里新建一...

php抛出异常与捕捉特定类型的异常详解

什么是异常? PHP 5 提供了一种新的面向对象的错误处理方法。 异常处理用于在指定的错误(异常)情况发生时改变脚本的正常流程。这种情况称为异常。 当异常被触发时,通常会发生:...

PHP读取文件内容后清空文件示例代码

复制代码 代码如下: $fh = fopen($path, "r+"); if( flock($fh, LOCK_EX) ){//加写锁 $old_content=json_decode...

PHP编程获取各个时间段具体时间的方法

本文实例讲述了PHP编程获取各个时间段具体时间的方法。分享给大家供大家参考,具体如下: <?php echo "今天:".date("Y-m-d")."<br&g...

PHP获取对象属性的三种方法实例分析

本文实例讲述了PHP获取对象属性的三种方法。分享给大家供大家参考,具体如下: 今天查看yii源码,发现yii\base\Model中的attribute()方法是通过反射获取对象的pub...