Translate amount of seconds to hours, minutes, seconds


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



Copy this code and paste it in your HTML
  1. Duration is a function used to turn seconds into a readable format, measured in weeks, days, hours, minutes and seconds.
  2. Highlight: PHP
  3.  
  4. <?php
  5. function duration($secs)
  6. {
  7. $vals = array('w' => (int) ($secs / 86400 / 7),
  8. 'd' => $secs / 86400 % 7,
  9. 'h' => $secs / 3600 % 24,
  10. 'm' => $secs / 60 % 60,
  11. 's' => $secs % 60);
  12.  
  13. $ret = array();
  14.  
  15. $added = false;
  16. foreach ($vals as $k => $v) {
  17. if ($v > 0 || $added) {
  18. $added = true;
  19. $ret[] = $v . $k;
  20. }
  21. }
  22.  
  23. return join(' ', $ret);
  24. }
  25. ?>
  26.  
  27. Sample usage
  28. Highlight: PHP
  29.  
  30. <?php
  31. $dateOfBirth = $someTimestamp;
  32. $ageInSeconds = time() - $dateOfBirth;
  33.  
  34. echo 'I am ' . duration($ageInSeconds) . ' old';
  35. ?>

URL: http://www.phpriot.com/d/code/date-time/duration/index.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.