[javascript] milliseconds to time in javascript

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

This question is related to javascript jquery

The answer is


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

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

This worked for me:

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

JSFiddle


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

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

try this function :-

_x000D_
_x000D_
function msToTime(ms) {_x000D_
  var d = new Date(null)_x000D_
  d.setMilliseconds(ms)_x000D_
  return d.toLocaleTimeString("en-US")_x000D_
}_x000D_
_x000D_
var ms = 4000000_x000D_
alert(msToTime(ms))
_x000D_
_x000D_
_x000D_


Not to reinvent the wheel, here is my favourite one-liner solution:

_x000D_
_x000D_
/**_x000D_
 * Convert milliseconds to time string (hh:mm:ss:mss)._x000D_
 *_x000D_
 * @param Number ms_x000D_
 *_x000D_
 * @return String_x000D_
 */_x000D_
function time(ms) {_x000D_
    return new Date(ms).toISOString().slice(11, -1);_x000D_
}_x000D_
_x000D_
console.log( time(12345 * 1000) );  // "03:25:45.000"
_x000D_
_x000D_
_x000D_

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:

_x000D_
_x000D_
/**_x000D_
 * Convert (milli)seconds to time string (hh:mm:ss[:mss])._x000D_
 *_x000D_
 * @param Boolean isSec_x000D_
 *_x000D_
 * @return String_x000D_
 */_x000D_
Number.prototype.toTime = function(isSec) {_x000D_
    var ms = isSec ? this * 1e3 : this,_x000D_
        lm = ~(4 * !!isSec),  /* limit fraction */_x000D_
        fmt = new Date(ms).toISOString().slice(11, lm);_x000D_
_x000D_
    if (ms >= 8.64e7) {  /* >= 24 hours */_x000D_
        var parts = fmt.split(/:(?=\d{2}:)/);_x000D_
        parts[0] -= -24 * (ms / 8.64e7 | 0);_x000D_
        return parts.join(':');_x000D_
    }_x000D_
_x000D_
    return fmt;_x000D_
};_x000D_
_x000D_
console.log( (12345 * 1000).toTime()     );  // "03:25:45.000"_x000D_
console.log( (123456 * 789).toTime()     );  // "27:03:26.784"_x000D_
console.log(  12345.       .toTime(true) );  // "03:25:45"_x000D_
console.log(  123456789.   .toTime(true) );  // "34293:33:09"
_x000D_
_x000D_
_x000D_


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

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/


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

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

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

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


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

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

An Easier solution would be the following:

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

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

_x000D_
_x000D_
class SuperDate extends Date {_x000D_
  get raceTime() {_x000D_
    return Math.floor(this/36e5).toString().padStart(2,'0')_x000D_
    + this.toISOString().slice(13, -1)_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('marathon', new SuperDate(11235200).raceTime)_x000D_
console.log('ironman', new SuperDate(40521100).raceTime)_x000D_
console.log('spartathlon', new SuperDate(116239000).raceTime)_x000D_
console.log('epoch', new SuperDate(new Date()).raceTime)
_x000D_
_x000D_
_x000D_

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

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


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