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

PHP将时间格式化几天前、几分钟前等

程序员文章站 2022-05-14 20:35:51
...
  1. class DateFormat
  2. {
  3. private static $_DIFF_FORMAT = array(
  4. 'DAY' => '%s天前',
  5. 'DAY_HOUR' => '%s天%s小时前',
  6. 'HOUR' => '%s小时',
  7. 'HOUR_MINUTE' => '%s小时%s分前',
  8. 'MINUTE' => '%s分钟前',
  9. 'MINUTE_SECOND' => '%s分钟%s秒前',
  10. 'SECOND' => '%s秒前',
  11. );
  12. /**
  13. * 友好格式化时间
  14. *
  15. * @param int 时间
  16. * @param array $formats
  17. * @return string
  18. */
  19. public static function diff($timestamp, $formats = null)
  20. {
  21. if ($formats == null) {
  22. $formats = self::$_DIFF_FORMAT;
  23. }
  24. /* 计算出时间差 */
  25. $seconds = time() - $timestamp;
  26. $minutes = floor($seconds / 60);
  27. $hours = floor($minutes / 60);
  28. $days = floor($hours / 24);
  29. if ($days > 0) {
  30. $diffFormat = 'DAY';
  31. } else {
  32. $diffFormat = ($hours > 0) ? 'HOUR' : 'MINUTE';
  33. if ($diffFormat == 'HOUR') {
  34. $diffFormat .= ($minutes > 0 && ($minutes - $hours * 60) > 0) ? '_MINUTE' : '';
  35. } else {
  36. $diffFormat = (($seconds - $minutes * 60) > 0 && $minutes > 0)
  37. ? $diffFormat.'_SECOND' : 'SECOND';
  38. }
  39. }
  40. $dateDiff = null;
  41. switch ($diffFormat) {
  42. case 'DAY':
  43. $dateDiff = sprintf($formats[$diffFormat], $days);
  44. break;
  45. case 'DAY_HOUR':
  46. $dateDiff = sprintf($formats[$diffFormat], $days, $hours - $days * 60);
  47. break;
  48. case 'HOUR':
  49. $dateDiff = sprintf($formats[$diffFormat], $hours);
  50. break;
  51. case 'HOUR_MINUTE':
  52. $dateDiff = sprintf($formats[$diffFormat], $hours, $minutes - $hours * 60);
  53. break;
  54. case 'MINUTE':
  55. $dateDiff = sprintf($formats[$diffFormat], $minutes);
  56. break;
  57. case 'MINUTE_SECOND':
  58. $dateDiff = sprintf($formats[$diffFormat], $minutes, $seconds - $minutes * 60);
  59. break;
  60. case 'SECOND':
  61. $dateDiff = sprintf($formats[$diffFormat], $seconds);
  62. break;
  63. }
  64. return $dateDiff;
  65. }
  66. }
  67. echo DateFormat::diff('1310455823');
  68. /* 33分钟47秒前 */
复制代码

几天, 几分钟, PHP