Skip to main content

Time conversions in JavaScript

function hoursToMinutes(hrs) {
  return hrs *= 60;
}

function hoursToSeconds(hrs) {
  return hrs *= 3600;
}

function minutesToHours(min) {
  var hrs = Math.floor(min / 60);
  min = min % 60;
  if (min < 10) {
    min = "0" + min;
  }
  return hrs + ":" + min;
}

function minutesToSeconds(min) {
  return min *= 60;
}

// Converts seconds to hours, providing result
// as a string in the form 'hours:minutes:seconds'.
function secondsToHours(sec) {
  var hrs = Math.floor(sec / 3600);
  var min = Math.floor((sec % 3600) / 60);
  sec = sec % 60;
  if (sec < 10) {
    sec = "0" + sec;
  }
  if (min < 10) {
    min = "0" + min;
  }
  return hrs + ":" + min + ":" + sec;
}

// Converts seconds to minutes, providing result
// as a string in the form 'minutes:seconds'.
function secondsToMinutes(sec) {
  var min = Math.floor(sec / 60);
  sec = sec % 60;
  if (sec < 10) {
    sec = "0" + sec;
  }
  if (min < 10) {
    min = "0" + min;
  }
  return min + ":" + sec;
}