I have a timecode that is in seconds, to three places past the decimal. (e.g. 10.675) I'd like to format it to read mm:ss (e.g. 00:32 or 23:04). Is there a Javascript or jQuery base function that does that? Whenever I search I only find how to add times to datepickers.
2 Answers
Try something like the below:
function formateDate( seconds ) {
var date = new Date(seconds * 1000);
return date.getMinutes() + ":" + date.getSeconds();
}
This will create a new date where you can focus on the time aspect. This will not work well if you need to go over 24 hours though. For that you'd need two dates that you compare. Or just do the calculations manually using divide and modulus.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/
Comments
I don't believe jQuery has any support by default for this, but it's fairly simple to write your own. For example:
function formatTime(seconds) {
var mins = Math.floor(seconds/60),
secs = Math.floor(seconds) - (60*mins);
return (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
}
However, this does not work well if the timecode is larger than 60 minutes, in which case you'd just need to add hours.