Page 1 of 1

How to convert seconds in to readable time using php

Posted: Mon Mar 01, 2010 12:19 am
by Neo
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.

Code: Select all

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;
} 

Code: Select all

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.