Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  64] [ 6]  / answers: 1 / hits: 142040  / 12 Years ago, mon, march 19, 2012, 12:00:00

I have this function which formats seconds to time



 function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return minutes + : + seconds;
}


it works great but i need a function to turn milliseconds to time and I cant seem to understand what i need to do to this function to return time in this format



mm:ss.mill
01:28.5568

More From » jquery

 Answers
13

Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:



function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;

return hrs + ':' + mins + ':' + secs + '.' + ms;
}


If you want it formatted as hh:mm:ss.sss then use:





function msToTime(s) {

// Pad to 2 or 3 digits, default is 2
function pad(n, z) {
z = z || 2;
return ('00' + n).slice(-z);
}

var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;

return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);
}

console.log(msToTime(55018))





Using some recently added language features, the pad function can be more concise:





function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
var pad = (n, z = 2) => ('00' + n).slice(-z);
return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);
}

// Current hh:mm:ss.sss UTC
console.log(msToTime(new Date() % 8.64e7))




[#86760] Saturday, March 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidan

Total Points: 72
Total Questions: 95
Total Answers: 121

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
aidan questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Sep 29, 21, 00:00, 3 Years ago
Sun, Sep 5, 21, 00:00, 3 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;