Converting Milliseconds To Minutes And Seconds With Javascript
Answer :
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);
With hours, 0-padding minutes and seconds:
var ms = 298999;
var d = new Date(1000*Math.round(ms/1000)); // round to nearest second
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
console.log(str); // 0:04:59
Here's my contribution if looking for
h:mm:ss
instead like I was:
function msConversion(millis) {
let sec = Math.floor(millis / 1000);
let hrs = Math.floor(sec / 3600);
sec -= hrs * 3600;
let min = Math.floor(sec / 60);
sec -= min * 60;
sec = '' + sec;
sec = ('00' + sec).substring(sec.length);
if (hrs > 0) {
min = '' + min;
min = ('00' + min).substring(min.length);
return hrs + ":" + min + ":" + sec;
}
else {
return min + ":" + sec;
}
}
Comments
Post a Comment