Converting milliseconds to minutes and seconds with Javascript

ElliotD picture ElliotD · Jan 22, 2014 · Viewed 127.8k times · Source

Soundcloud's API gives the duration of it's tracks as milliseconds. JSON looks like this:

"duration": 298999

I've tried many functions I found on here to no avail. I'm just looking for something to convert that number to something like looks like this:

4:59

Here's one that got close, but doesn't work. It doesn't stop the seconds at 60. It goes all the way to 99 which makes no sense. Try entering "187810" as a value of ms, for example.

var ms = 298999,
min = Math.floor((ms/1000/60) << 0),
sec = Math.floor((ms/1000) % 60);

console.log(min + ':' + sec);

Thanks for your help!

If you could add in support for hours, too, I would be grateful.

Answer

maerics picture maerics · Jan 22, 2014
function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

millisToMinutesAndSeconds(298999); // "4:59"
millisToMinutesAndSeconds(60999);  // "1:01"

As User HelpingHand pointed in the comments the return statement should be:

return (
  seconds == 60 ?
  (minutes+1) + ":00" :
  minutes + ":" + (seconds < 10 ? "0" : "") + seconds
);