当前位置:Gxlcms > PHP教程 > PHP将时间格式化几天前、几分钟前等

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

时间:2021-07-01 10:21:17 帮助过:29人阅读

  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

人气教程排行