Posted By

Sixer on 05/25/07


Tagged

time clock timestamp translate hours minutes seconds duration


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

vali29
hudge
Nix
etangle
sveggiani


Translate amount of seconds to hours, minutes, seconds


 / Published in: PHP
 

URL: http://www.phpriot.com/d/code/date-time/duration/index.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. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: darksider on April 30, 2010

nice man, cheers =)

You need to login to post a comment.