欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

将时间转成几天前,几小时等的格式

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

几天, 转成