首頁 >後端開發 >php教程 >PHP將時間格式化幾天前、幾分鐘前等

PHP將時間格式化幾天前、幾分鐘前等

WBOY
WBOY原創
2016-07-25 08:45:211017瀏覽
  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


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn