Convert seconds to hh:mm:ss


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



Copy this code and paste it in your HTML
  1. function sec2hms ($sec, $padHours = false) {
  2.  
  3. $hms = "";
  4.  
  5. // there are 3600 seconds in an hour, so if we
  6. // divide total seconds by 3600 and throw away
  7. // the remainder, we've got the number of hours
  8. $hours = intval(intval($sec) / 3600);
  9.  
  10. // add to $hms, with a leading 0 if asked for
  11. $hms .= ($padHours)
  12. ? str_pad($hours, 2, "0", STR_PAD_LEFT). ':'
  13. : $hours. ':';
  14.  
  15. // dividing the total seconds by 60 will give us
  16. // the number of minutes, but we're interested in
  17. // minutes past the hour: to get that, we need to
  18. // divide by 60 again and keep the remainder
  19. $minutes = intval(($sec / 60) % 60);
  20.  
  21. // then add to $hms (with a leading 0 if needed)
  22. $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ':';
  23.  
  24. // seconds are simple - just divide the total
  25. // seconds by 60 and keep the remainder
  26. $seconds = intval($sec % 60);
  27.  
  28. // add to $hms, again with a leading 0 if needed
  29. $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
  30.  
  31. return $hms;
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.