Home  >  Article  >  Backend Development  >  PHP formats time days ago, minutes ago, etc.

PHP formats time days ago, minutes ago, etc.

WBOY
WBOYOriginal
2016-07-25 08:45:21992browse
  1. class DateFormat
  2. {
  3. private static $_DIFF_FORMAT = array(
  4. 'DAY' => '%s days ago',
  5. 'DAY_HOUR' => '%s days %s hours ago',
  6. 'HOUR' => '%s hours',
  7. 'HOUR_MINUTE' => '%s hours %s minutes ago',
  8. 'MINUTE' => '%s minutes ago',
  9. 'MINUTE_SECOND ' => '%s minutes %s seconds ago',
  10. 'SECOND' => '%s seconds ago',
  11. );
  12. /**
  13. * Friendly formatted time
  14. *
  15. * @param int time
  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. /* Calculate the time difference*/
  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 minutes 47 seconds ago*/
Copy code

Days, minutes, PHP


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
Previous article:PHP decompress zip fileNext article:PHP decompress zip file