I have this function which formats seconds to time
function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
JSFiddle
Prons:
00:00:00.0
You can put it into a helper file
export const msecToTime = ms => {
const milliseconds = ms % 1000
const seconds = Math.floor((ms / 1000) % 60)
const minutes = Math.floor((ms / (60 * 1000)) % 60)
const hours = Math.floor((ms / (3600 * 1000)) % 3600)
return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
seconds < 10 ? '0' + seconds : seconds
}.${milliseconds}`
}
Not to reinvent the wheel, here is my favourite one-liner solution:
/**
* Convert milliseconds to time string (hh:mm:ss:mss).
*
* @param Number ms
*
* @return String
*/
function time(ms) {
return new Date(ms).toISOString().slice(11, -1);
}
console.log( time(12345 * 1000) ); // "03:25:45.000"
Method Date.prototype.toISOString() returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ
. This method is supported in all modern browsers (IE9+) and JavaScript engines.
UPDATE: The solution above is always limited to range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000
). To make it working with any input value, I have extended it into a nice universal prototype method:
/**
* Convert (milli)seconds to time string (hh:mm:ss[:mss]).
*
* @param Boolean isSec
*
* @return String
*/
Number.prototype.toTime = function(isSec) {
var ms = isSec ? this * 1e3 : this,
lm = ~(4 * !!isSec), /* limit fraction */
fmt = new Date(ms).toISOString().slice(11, lm);
if (ms >= 8.64e7) { /* >= 24 hours */
var parts = fmt.split(/:(?=\d{2}:)/);
parts[0] -= -24 * (ms / 8.64e7 | 0);
return parts.join(':');
}
return fmt;
};
console.log( (12345 * 1000).toTime() ); // "03:25:45.000"
console.log( (123456 * 789).toTime() ); // "27:03:26.784"
console.log( 12345. .toTime(true) ); // "03:25:45"
console.log( 123456789. .toTime(true) ); // "34293:33:09"
try this function :-
function msToTime(ms) {
var d = new Date(null)
d.setMilliseconds(ms)
return d.toLocaleTimeString("en-US")
}
var ms = 4000000
alert(msToTime(ms))
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();
Editing RobG's solution and using JavaScript's Date().
function msToTime(ms) {
function addZ(n) {
return (n<10? '0':'') + n;
}
var dt = new Date(ms);
var hrs = dt.getHours();
var mins = dt.getMinutes();
var secs = dt.getSeconds();
var millis = dt.getMilliseconds();
var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
return tm;
}