Home >Backend Development >PHP Tutorial >Convert time to days ago, hours, etc. format

Convert time to days ago, hours, etc. format

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 08:45:421088browse
将时间转成几天前,几小时等的格式,如: “1天前”,“2个月前”等。
  1. function prettyDate($date){
  2. $time = strtotime($date);
  3. $now = time();
  4. $ago = $now - $time;
  5. if($ago < 60){
  6. $when = round($ago);
  7. $s = ($when == 1)?"second":"seconds";
  8. return "$when $s ago";
  9. }elseif($ago < 3600){
  10. $when = round($ago / 60);
  11. $m = ($when == 1)?"minute":"minutes";
  12. return "$when $m ago";
  13. }elseif($ago >= 3600 && $ago < 86400){
  14. $when = round($ago / 60 / 60);
  15. $h = ($when == 1)?"hour":"hours";
  16. return "$when $h ago";
  17. }elseif($ago >= 86400 && $ago < 2629743.83){
  18. $when = round($ago / 60 / 60 / 24);
  19. $d = ($when == 1)?"day":"days";
  20. return "$when $d ago";
  21. }elseif($ago >= 2629743.83 && $ago < 31556926){
  22. $when = round($ago / 60 / 60 / 24 / 30.4375);
  23. $m = ($when == 1)?"month":"months";
  24. return "$when $m ago";
  25. }else{
  26. $when = round($ago / 60 / 60 / 24 / 365);
  27. $y = ($when == 1)?"year":"years";
  28. return "$when $y ago";
  29. }
  30. }
  31. echo prettyDate("2012-07-22 12:23:45")."
    ";
  32. echo prettyDate("2010-11-12 22:25:45")."
    ";
  33. echo prettyDate("2012-01-01 01:00:00")."
    ";
  34. echo prettyDate("2001-05-30 00:00:00")."
    ";
复制代码

几天, 转成


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn