seconds to hh mm ss

Convert seconds to hh-mm-ss format

by Steven Martin

HTML

<div id="seconds-example1"></div>
<div id="seconds-example2"></div>
<div id="seconds-example3"></div>

JavaScript

/** 
 * Convert seconds to hh-mm-ss format.
 * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
  var hours   = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // round seconds
  seconds = Math.round(seconds * 100) / 100

  var result = (hours < 10 ? "0" + hours : hours);
      result += "-" + (minutes < 10 ? "0" + minutes : minutes);
      result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

// example
var seconds1 = SecondsTohhmmss(86400);
var seconds2 = SecondsTohhmmss(20);
var seconds3 = SecondsTohhmmss(70);

document.getElementById("seconds-example1").innerHTML = seconds1;
document.getElementById("seconds-example2").innerHTML = seconds2;
document.getElementById("seconds-example3").innerHTML = seconds3;