nice time duration in php


/ Published in: PHP
Save to your folder(s)

a flexible function for making time periods readable


Copy this code and paste it in your HTML
  1. /**
  2.  * A function for making time periods readable
  3.  *
  4.  * @author Aidan Lister <[email protected]>
  5.  * @version 2.0.1
  6.  * @link http://aidanlister.com/2004/04/making-time-periods-readable/
  7.  * @param int number of seconds elapsed
  8.  * @param string which time periods to display
  9.  * @param bool whether to show zero time periods
  10.  */
  11. function time_duration($seconds, $use = null, $zeros = false)
  12. {
  13. // Define time periods
  14. $periods = array (
  15. 'years' => 31556926,
  16. 'Months' => 2629743,
  17. 'weeks' => 604800,
  18. 'days' => 86400,
  19. 'hours' => 3600,
  20. 'minutes' => 60,
  21. 'seconds' => 1
  22. );
  23.  
  24. // Break into periods
  25. $seconds = (float) $seconds;
  26. $segments = array();
  27. foreach ($periods as $period => $value) {
  28. if ($use && strpos($use, $period[0]) === false) {
  29. continue;
  30. }
  31. $count = floor($seconds / $value);
  32. if ($count == 0 && !$zeros) {
  33. continue;
  34. }
  35. $segments[strtolower($period)] = $count;
  36. $seconds = $seconds % $value;
  37. }
  38.  
  39. // Build the string
  40. $string = array();
  41. foreach ($segments as $key => $value) {
  42. $segment_name = substr($key, 0, -1);
  43. $segment = $value . ' ' . $segment_name;
  44. if ($value != 1) {
  45. $segment .= 's';
  46. }
  47. $string[] = $segment;
  48. }
  49.  
  50. return implode(', ', $string);
  51. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.