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

yipeiwu_com4年前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中可以轻松的使用下面的语句实现...

php短网址和数字之间相互转换的方法

本文实例讲述了php短网址和数字之间相互转换的方法。分享给大家供大家参考。具体实现方法如下: <?php /** * 将数字转为短网址代码 * * @param...

PHP实现的迷你漂流瓶

本文实例讲述了PHP实现的迷你漂流瓶。分享给大家供大家参考。具体如下: mysql.php: <?php mysql_connect('127.0.0.1','root...

3种方法轻松处理php开发中emoji表情的问题

背景 做微信开发的时候就会发现,存储微信昵称必不可少。 可这万恶的微信支持emoji表情做昵称,这就有点蛋疼了 一般Mysql表设计时,都是用UTF8字符集的。把带有emoji的昵称字段...

php setcookie函数的参数说明及其用法

php setcookie函数的参数说明 用法: setcookie(name,value,expire,path,domain,secure) 参数 描述 name 必需。规定 coo...