## Posted By

mikeejay on 10/24/06

# 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.
22. if (\$hours > 0){
23. \$hms .= (\$useColon)
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)
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)