Monthly Archive for July, 2006

Convert Seconds to Something More Friendly

Here are two functions to help you convert a number of seconds to something more friendly. Update: bug fix on seconds evaluating to more than one hour.

function secondsToFriendly($seconds) {
### this function takes a number of seconds and returns HH:MM:SS

  $st = $seconds;
  $s = 0;
  $m = 0;
  $h = 0;
  while ($st > 0) {
    if ($st < 60) { # only seconds left
      $s = $st;
      $st = 0;
 
    } else if ($st < 3600) { # minutes left
      $op = floor($st / 60);
      $m = $op;
      $st -= $op * 60;
    } else { # hours
      $op = floor($st / 3600);
      $h = $op;
      $st -= $op * 3600;
 
    }
  } # end of while
  return pad($h) .":". pad($m) .":". pad($s);
}
 
function pad($n, $pad = 2) {
### zero-pads a number
  $temp = "";
  for ($i = 0; $i < $pad; $i++) { $temp .= "0"; }
  $temp .= $n;
 
  return substr($temp, strlen($temp) - $pad);
}