0

I am trying to format time. I have a function that returns seconds, minutes, and hours, but I have an issue with the minutes. After the minute hits 60, I would like to reset the minute time to 0 and restart the clock. Any ideas?

function formatTime(seconds) {
  hours = Math.floor((seconds / 60) / 60);
  hours = (hours >= 10) ? minutes : "0" + hours;
  minutes = Math.floor(seconds / 60);
  minutes = (minutes >= 10) ? minutes : "0" + minutes;
  seconds = Math.floor(seconds % 60);
  seconds = (seconds >= 10) ? seconds : "0" + seconds;

  if (duration >= hours) {
    return hours + ":" + minutes + ":" + seconds;
  } else {
    return minutes + ":" + seconds;
  }
}

If you have any other questions, let me know. This function is being used to format an audio clip's duration counter.

Wes Cossick
  • 2,923
  • 2
  • 20
  • 35
  • 1
    Unless this is for coursework, I'd suggest using a library such as [DateJS](http://datejs.com) or [MomentJS](http://momentjs.com) instead. Date wrangling in JS is an almighty pain. – Rory McCrossan Jul 07 '15 at 14:50
  • If you don't have a limitation on libraries, take a look at http://momentjs.com/ – SDekov Jul 07 '15 at 14:50
  • Duplicate of https://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript or https://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss/6313008#6313008 – svenhornberg Jul 07 '15 at 14:51
  • Good way is to use a library for this. If you want to make it on your own with the provided snippet, substract the hours and minutes from the inital seconds. hours = `Math.floor(seconds / 3600)`, minutes = `Math.floor( seconds - (hours * 3600))` etc. – Stefan Jul 07 '15 at 14:53

2 Answers2

0

You should do the following:

  • count the hours
  • substract hours * 60 * 60 from seconds
  • count the minutes
  • substract minutes * 60 from seconds
  • the remainder are the seconds

By the way, for time and date calculations, I absolutely recommend MomentJS.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
0

Thank you for all your help guys. Based off many recommendations, I will look towards using momentjs. However with the help of some of these posts, I also managed to get my format time function to work. It now does what I need and looks like this:

function formatTime(seconds) {
  hours = Math.floor((seconds / 3600));
  hours = (hours >= 10) ? minutes : "0" + hours;
  minutes = Math.floor((seconds - (hours * 3600)) / 60);
  minutes = (minutes >= 10) ? minutes : "0" + minutes;
  seconds = Math.floor(seconds - hours * 3600) - (minutes * 60);
  seconds = (seconds >= 10) ? seconds : "0" + seconds;

  if (duration >= hours) {
    return hours + ":" + minutes + ":" + seconds;
  } else {
    return minutes + ":" + seconds;
  }
}