Posted By

mikeejay on 10/24/06


Tagged

time second convert


Versions (?)

sec2hms


 / Published in: PHP
 

converts seconds to h:m:s

  1. /**
  2.  * Convert seconds to a string in this format "NN tim NN min NN sek"
  3.  * If $useColon is TRUE it returns h:m:s
  4.  *
  5.  *
  6.  * @param integer $sec
  7.  * @param bool $useColon
  8.  * @return string $hms
  9.  */
  10. function sec2hms($sec, $useColon = false)
  11. {
  12.  
  13. // holds formatted string
  14. $hms = "";
  15.  
  16. // there are 3600 seconds in an hour, so if we
  17. // divide total seconds by 3600 and throw away
  18. // the remainder, we've got the number of hours
  19. $hours = intval(intval($sec) / 3600);
  20.  
  21. // add to $hms, with a leading 0 if asked for
  22. if ($hours > 0){
  23. $hms .= ($useColon)
  24. ? str_pad($hours, 2, "0", STR_PAD_LEFT). ':'
  25. : $hours. ' tim ';
  26. }elseif ($useColon){
  27. $hms .= '00:';
  28. }
  29.  
  30. // dividing the total seconds by 60 will give us
  31. // the number of minutes, but we're interested in
  32. // minutes past the hour: to get that, we need to
  33. // divide by 60 again and keep the remainder
  34. $minutes = intval(($sec / 60) % 60);
  35.  
  36. // then add to $hms (with a leading 0 if needed)
  37. if ($minutes > 0)
  38. $hms .= ($useColon)
  39. ? str_pad($minutes, 2, "0", STR_PAD_LEFT). ':'
  40. : $minutes. ' min ';
  41.  
  42. // seconds are simple - just divide the total
  43. // seconds by 60 and keep the remainder
  44. $seconds = intval($sec % 60);
  45.  
  46. // add to $hms, again with a leading 0 if needed
  47. $hms .= ($useColon)
  48. ? str_pad($seconds, 2, "0", STR_PAD_LEFT)
  49. : $seconds. ' sek ';
  50.  
  51. return $hms;
  52. }

Report this snippet  

You need to login to post a comment.