milliseconds to time in javascript

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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))

Solution 2 - Javascript

Here is my favourite one-liner solution:

new Date(12345 * 1000).toISOString().slice(11, -1);  // "03:25:45.000"

Method Date.prototype.toISOString() returns a string in the 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 Node.

This one-liner is limited to a range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). The following code is able to format correctly any number of milliseconds (shaped in a handy prototype method):

/**
 * Convert (milli)seconds to time string (hh:mm:ss[:mss]).
 *
 * @param Boolean seconds
 *
 * @return String
 */
Number.prototype.toTimeString = function(seconds) {
    var _24HOURS = 8.64e7;  // 24*60*60*1000

    var ms = seconds ? this * 1000 : this,
        endPos = ~(4 * !!seconds),  // to trim "Z" or ".sssZ"
        timeString = new Date(ms).toISOString().slice(11, endPos);

    if (ms >= _24HOURS) {  // to extract ["hh", "mm:ss[.mss]"]
        var parts = timeString.split(/:(?=\d{2}:)/);
        parts[0] -= -24 * Math.floor(ms / _24HOURS);
        timeString = parts.join(":");
    }

    return timeString;
};

console.log( (12345 * 1000).toTimeString()     );  // "03:25:45.000"
console.log( (123456 * 789).toTimeString()     );  // "27:03:26.784"
console.log(  12345.       .toTimeString(true) );  // "03:25:45"
console.log(  123456789.   .toTimeString(true) );  // "34293:33:09"

Solution 3 - Javascript

function millisecondsToTime(milli)
{
      var milliseconds = milli % 1000;
      var seconds = Math.floor((milli / 1000) % 60);
      var minutes = Math.floor((milli / (60 * 1000)) % 60);

      return minutes + ":" + seconds + "." + milliseconds;
}

Solution 4 - Javascript

Why not use the Date object like this?

let getTime = (milli) => {
  let time = new Date(milli);
  let hours = time.getUTCHours();
  let minutes = time.getUTCMinutes();
  let seconds = time.getUTCSeconds();
  let milliseconds = time.getUTCMilliseconds();
  return hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
}

https://jsfiddle.net/4sdkpso7/6/

Solution 5 - Javascript

function millisecondsToTime(millisecs){
  var ms = Math.abs(millisecs) % 1000;
  var secs = (millisecs < 0 ? -1 : 1) * ((Math.abs(millisecs) - ms) / 1000);
  ms = '' + ms;
  ms = '000'.substring(ms.length) + ms;
  return secsToTime(secs) + '.' + ms;
}

Solution 6 - Javascript

Here is a filter that use:

app.filter('milliSecondsToTimeCode', function () {
    return function msToTime(duration) {
        var milliseconds = parseInt((duration % 1000) / 100)
            , seconds = parseInt((duration / 1000) % 60)
            , minutes = parseInt((duration / (1000 * 60)) % 60)
            , hours = parseInt((duration / (1000 * 60 * 60)) % 24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
    };
});

Just add it to your expression as such

{{milliseconds | milliSecondsToTimeCode}}

Solution 7 - Javascript

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;
}

Solution 8 - Javascript

This worked for me:

var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();

JSFiddle

Solution 9 - Javascript

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
    if (startDate != null) {
      var launchDate = new Date(startDate);
       var day = launchDate.getUTCDate();
      var month = monthNames[launchDate.getMonth()];
      var year = launchDate.getFullYear(); 
      var min = launchDate.getMinutes();
      var hour = launchDate.getHours();
      var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
   
      return  day + " " + month + " " + year + " - " + time + ""  ;
    }
    return "";
   }

Solution 10 - Javascript

function msToTime(s) {

  var d = new Date(s); 
  var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " 
    + ("0" + d.getHours()).slice(-2) 
    + ":" + ("0" + d.getMinutes()).slice(-2)
    + ":" + ("0" + d.getSeconds()).slice(-2)
    +"."+d.getMilliseconds();

  return datestring;	  

}

output 16-10-2019 18:55:32.605

Solution 11 - Javascript

Prons:

  • simple and clean code; easy to modify for your needs
  • support any amount of hours (>24 hrs is ok)
  • format time as 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}`
}

Solution 12 - Javascript

Simplest Way

let getTime = (Time)=>{
    let Hours = Time.getHours();
    let Min = Time.getMinutes();
    let Sec = Time.getSeconds();

    return `Current time ${Hours} : ${Min} : ${Sec}`;
}

console.log(getTime(new Date()));

Solution 13 - Javascript

var 
         /**
         * Parses time in milliseconds to time structure
         * @param {Number} ms
         * @returns {Object} timeStruct
         * @return {Integer} timeStruct.d days
         * @return  {Integer} timeStruct.h hours
         * @return  {Integer} timeStruct.m minutes
         * @return  {Integer} timeStruct.s seconds
         */
        millisecToTimeStruct = function (ms) {
            var d, h, m, s;
            if (isNaN(ms)) {
                return {};
            }
            d = ms / (1000 * 60 * 60 * 24);
            h = (d - ~~d) * 24;
            m = (h - ~~h) * 60;
            s = (m - ~~m) * 60;
            return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
        },

        toFormattedStr = function(tStruct){
           var res = '';
           if (typeof tStruct === 'object'){
               res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
           }
           return res;
        };

// client code:
var
        ms = new Date().getTime(),
        timeStruct = millisecToTimeStruct(ms),
        formattedString = toFormattedStr(timeStruct);
alert(formattedString);

Solution 14 - Javascript

var secondsToTime = function(duration) {
  var date = new Date(duration);

  return "%hours:%minutes:%seconds:%milliseconds"
    .replace('%hours', date.getHours())
    .replace('%minutes', date.getMinutes())
    .replace('%seconds', date.getSeconds())
    .replace('%milliseconds', date.getMilliseconds());
}

Solution 15 - Javascript

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))

Solution 16 - Javascript

A possible solution that worked for my case. It turns milliseconds into hh:ss time:

function millisecondstotime(ms) {
var x = new Date(ms);
var y = x.getHours();
if (y < 10) {
y = '0' + y;
} 
var z = x.getMinutes();
if (z < 10) {
    z = '0' + z;
} 
return y + ':' + z;
}

Solution 17 - Javascript

This is the solution I got and working so good!

function msToHuman(duration) {
var milliseconds = parseInt((duration%1000)/100)
    seconds = parseInt((duration/1000)%60)
    minutes = parseInt((duration/(1000*60))%60)
    hours = parseInt((duration/(1000*60*60))%24);


return hours + "hrs " minutes + "min " + seconds + "sec " + milliseconds + 'ms';
}

Solution 18 - Javascript

Most of the answers don't cover cases where there is more than 24h. This one does. I suggest extending Date object:

class SuperDate extends Date {
  get raceTime() {
    return Math.floor(this/36e5).toString().padStart(2,'0')
    + this.toISOString().slice(13, -1)
  }
}

console.log('marathon', new SuperDate(11235200).raceTime)
console.log('ironman', new SuperDate(40521100).raceTime)
console.log('spartathlon', new SuperDate(116239000).raceTime)
console.log('epoch', new SuperDate(new Date()).raceTime)

This approach works great with Firestore Timestamp objects which are similar to what you need:

class SuperDate extends Date {
  fromFirestore (timestamp) {
    return new SuperDate(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)
  }
  get raceTime() {
    return Math.floor(this/36e5).toString().padStart(2,'0')
    + this.toISOString().slice(13, -1)
  }
}

const timestamp = {seconds: 11235, nanoseconds: 200000000}

console.log('timestamp', new SuperDate().fromFirestore(timestamp))
console.log('marathon', new SuperDate().fromFirestore(timestamp).raceTime)

Solution 19 - Javascript

An Easier solution would be the following:

var d = new Date();
var n = d.getMilliseconds(); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt ElhotibyView Question on Stackoverflow
Solution 1 - JavascriptRobGView Answer on Stackoverflow
Solution 2 - JavascriptVisioNView Answer on Stackoverflow
Solution 3 - JavascriptRichard J. Ross IIIView Answer on Stackoverflow
Solution 4 - JavascriptsissonbView Answer on Stackoverflow
Solution 5 - JavascriptMike SamuelView Answer on Stackoverflow
Solution 6 - JavascriptEwald BosView Answer on Stackoverflow
Solution 7 - Javascriptuser1321244View Answer on Stackoverflow
Solution 8 - JavascriptEugeneView Answer on Stackoverflow
Solution 9 - Javascriptuser3729215View Answer on Stackoverflow
Solution 10 - JavascriptFilippoGView Answer on Stackoverflow
Solution 11 - JavascriptRoman PodlinovView Answer on Stackoverflow
Solution 12 - JavascriptMD Mahmudul HasanView Answer on Stackoverflow
Solution 13 - JavascriptSergeyView Answer on Stackoverflow
Solution 14 - JavascriptmrdedView Answer on Stackoverflow
Solution 15 - JavascriptVikas GautamView Answer on Stackoverflow
Solution 16 - Javascriptb1919676View Answer on Stackoverflow
Solution 17 - Javascriptferpalma21.ethView Answer on Stackoverflow
Solution 18 - JavascriptradulleView Answer on Stackoverflow
Solution 19 - JavascriptKbdavis07View Answer on Stackoverflow