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

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

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

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

  1. // convert a date into a string that tells how long ago
  2. // that date was.... eg: 2 days ago, 3 minutes ago.
  3. function ago($d) {
  4. $c = getdate();
  5. $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
  6. $display = array('year', 'month', 'day', 'hour', 'minute', 'second');
  7. $factor = array(0, 12, 30, 24, 60, 60);
  8. $d = datetoarr($d);
  9. for ($w = 0; $w < 6; $w++) {
  10. if ($w > 0) {
  11. $c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
  12. $d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
  13. }
  14. if ($c[$p[$w]] - $d[$p[$w]] > 1) {
  15. return ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
  16. }
  17. }
  18. return '';
  19. }
  20. // you can replace this if need be.
  21. // This converts my dates returned from a mysql date string
  22. // into an array object similar to that returned by getdate().
  23. function datetoarr($d) {
  24. preg_match("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2})([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/",$d,$matches);
  25. return array(
  26. 'seconds' => $matches[10],
  27. 'minutes' => $matches[8],
  28. 'hours' => $matches[6],
  29. 'mday' => $matches[5],
  30. 'mon' => $matches[3],
  31. 'year' => $matches[1],
  32. );
  33. }