Skip to content

Instantly share code, notes, and snippets.

@edwinwebb
Created November 18, 2011 16:07
Show Gist options
  • Save edwinwebb/1376880 to your computer and use it in GitHub Desktop.
Save edwinwebb/1376880 to your computer and use it in GitHub Desktop.
Javascript Media Seconds to MM:SS:MS string
secondsToTimeString = function (seconds) {
var ms = Math.floor((seconds*1000) % 1000);
var s = Math.floor(seconds%60);
var m = Math.floor((seconds*1000/(1000*60))%60);
var strFormat = "MM:SS:XX";
if(s < 10) s = "0" + s;
if(m < 10) m = "0" + m;
if(ms < 10) ms = "0" + ms;
strFormat = strFormat.replace(/MM/, m);
strFormat = strFormat.replace(/SS/, s);
strFormat = strFormat.replace(/XX/, ms.toString().slice(0,2));
return strFormat;
}
@justswim
Copy link

justswim commented Dec 2, 2017

I believe there is a small bug in this code. Line 10 should be if(ms < 100) ms = "0" + ms;.

Without the fix, the function would run as follows:

// outputs "00:00:50"
secondsToTimeString(0.05)

But this is incorrect, as it should output "00:00:05".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment