PHP: Display seconds as hours, minutes and seconds

This is very straightforward: pass in a number of seconds, and you'll get a string back along the lines of "1:01:23". If you want a leading zero for less than 10 hours ("01:01:23" in our example), call the function with the second parameter set to true.

<?php

function sec2hms ($sec, $padHours = false) 
{

  // do the hours first: there are 3600 seconds in an hour, so if we divide
  // the total number of seconds by 3600 and throw away the remainder, we're
  // left with the number of hours in those seconds
  $hours = intval(intval($sec) / 3600); 

  // start our return string with the hours (with a leading 0 if asked for)
  if ($padHours) {
    $hms = str_pad($hours, 2, "0", STR_PAD_LEFT). ":";
  } else {
    $hms = $hours. ":";
  }

  // dividing the total seconds by 60 will give us the number of minutes
  // in total, but we're interested in *minutes past the hour* and to get
  // this, we have to divide by 60 again and then use the remainder
  $minutes = intval(($sec / 60) % 60); 

  // add minutes to $hms (with a leading 0 if needed)
  $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";

  // seconds past the minute are found by dividing the total number of seconds
  // by 60 and using the remainder
  $seconds = intval($sec % 60); 

  // add seconds to $hms (with a leading 0 if needed)
  $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);

  // done!
  return $hms;

}

?>
		

Please do get in touch if you have any questions or suggestions for improvement.