Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting milliseconds to minutes and seconds with Javascript

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.

like image 757
ElliotD Avatar asked Jan 22 '14 21:01

ElliotD


People also ask

How do you convert milliseconds to minutes and seconds?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60). The print output from Milliseconds to minutes and seconds.

How do you convert milliseconds to hours minutes seconds?

To convert milliseconds to hours, minutes, seconds:Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours. Add a leading zero if the values are less than 10 to format them consistently.

How do you convert milliseconds to seconds in react JS?

Convert to Seconds const milliseconds = 76329456; To get the seconds, we can divide the milliseconds by 1000.


1 Answers

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 ); 
like image 78
maerics Avatar answered Sep 30 '22 18:09

maerics