服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - php将日期格式转换成xx天前的格式

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

2020-09-19 21:56不吃皮蛋 PHP教程

这篇文章主要介绍了php将日期格式转换成xx天前的格式,涉及php时间操作及正则匹配的技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了php将日期格式转换成xx天前格式的方法。分享给大家供大家参考。具体如下:

这段代码可以把时间格式化成3天前,5秒前,2年前的形式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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程序设计有所帮助。

延伸 · 阅读

精彩推荐