UltraMega Tech.
3Jun/097

Snippet: Converting Seconds to Readable Time (PHP & JS)

Sometimes, you might need to convert an integer representing seconds into a format that is easier to read. These functions can be used to turn a number of seconds into a simple format of HH:MM:SS, with leading zeros (ex. 15272 = 04:14:32). This can be used for countdown scripts, which is why I also include both a PHP and a JavaScript version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function formatTime($secs) {
   $times = array(3600, 60, 1);
   $time = '';
   $tmp = '';
   for($i = 0; $i < 3; $i++) {
      $tmp = floor($secs / $times[$i]);
      if($tmp < 1) {
         $tmp = '00';
      }
      elseif($tmp < 10) {
         $tmp = '0' . $tmp;
      }
      $time .= $tmp;
      if($i < 2) {
         $time .= ':';
      }
      $secs = $secs % $times[$i];
   }
   return $time;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function formatTime(secs){
   var times = new Array(3600, 60, 1);
   var time = '';
   var tmp;
   for(var i = 0; i < times.length; i++){
      tmp = Math.floor(secs / times[i]);
      if(tmp < 1){
         tmp = '00';
      }
      else if(tmp < 10){
         tmp = '0' + tmp;
      }
      time += tmp;
      if(i < 2){
         time += ':';
      }
      secs = secs % times[i];
   }
   return time;
}

Usage

Both functions are identical in functionality: they accept seconds as an integer and return the formatted time as a string. You can easily extend it to return days, weeks, etc. just by adding those units in seconds to the array on the first line.

Posted by Steve

Comments (7) Trackbacks (1)
  1. How to convert seconds to YearMonthDateHourMinuteSecond?

  2. WOW! I couldn’t find this anywhere, thank you… saved a large headache of figuring out the math myself…. I feel like PHP should have a built in function for this (javascript too..) like sectoamt() would be a good name for it ;)

    I’m using it to compare two times and return the difference (like a million times).

    Thanks again.

  3. This works too:

    function formatTime($secs) {
    	return str_pad(floor($secs/3600),2,"0",STR_PAD_LEFT).":".
    		str_pad(floor(($secs%3600)/60),2,"0",STR_PAD_LEFT).":".
    		str_pad($secs%60,2,"0",STR_PAD_LEFT);
    }
  4. date(‘H:i:s’, $secs) when you have less then 25 hours :)

    I am searching for something already available in PHP too

  5. Even shorter:

    function formatTime($secs) {
    return sprintf(‘%02u:%02u:%02u’, floor($secs/3600), floor($secs%3600/60), $secs%60);
    }

    Please (re)format at will.

  6. Even shorter (sorry for repost):

    sprintf(‘%02u:%02u:%02u’, $secs/3600, $secs%3600/60, $secs%60);


Leave a comment

(required)