77

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
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321

19 Answers19

145

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))
RobG
  • 142,382
  • 31
  • 172
  • 209
78

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"
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • @Ziarno Not sure how React Native works but if it uses modern JS processor on behind, this code should be executed. – VisioN Jan 23 '17 at 12:44
  • hmm you're right, it does work. Must have had a different bug, sorry – Ziarno Jan 24 '17 at 12:32
  • This works for ms less than 24h. Every 24h, hours will start from 0 again. – haiiaaa Mar 31 '17 at 10:48
  • @haiiaaa You are right, it has a limitation. Please check the updated answer, I have added the extended solution, which works nicely with any number hours in milliseconds. – VisioN Mar 31 '17 at 12:16
  • Thanks it helper me – Vision Coderz Jul 16 '17 at 14:29
  • Okay this must be the shortest solution out there. I ended up with this `new Date(MILLISECONDS).toISOString().slice(14, -1).split('.').join(':')` which gives me the `mm:ss:SSS` format I needed for animation playback. – Hooman Askari Nov 29 '21 at 07:54
26
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;
}
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
16

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/

sissonb
  • 3,730
  • 4
  • 27
  • 54
  • 1
    When I add 18000 (ie. 18 secs in milliseconds) and call time.getMinutes() it returns 30 mins, and time.getSeconds() it returns 18 secs, as I see the getMinutes consider the input as if it is in seconds. wheras getSeconds consider it in milliseconds, Is there a way to just pass milliseconds and the time.get**** method returns correct time. In my case I need output to be 0 mins 18 secs. – Rajshekar Reddy Sep 22 '14 at 15:20
  • @RajshekarReddy I fixed that issue by using the UTC getters. – sissonb Jun 03 '17 at 02:05
3

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}}
Ewald Bos
  • 1,560
  • 1
  • 20
  • 33
3

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}`
}
Roman Podlinov
  • 23,806
  • 7
  • 41
  • 60
3
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;
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
2

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;
}
user1321244
  • 57
  • 1
  • 2
  • 12
1

This worked for me:

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

JSFiddle

Eugene
  • 2,965
  • 2
  • 34
  • 39
  • 1
    The `getHours()` method returns the hour (from 0 to 23) of the specified date and time. So, if the milliseconds represent more than 24 hs, this is not going to work – IvanRF Jun 01 '16 at 22:09
1
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 "";
   }
1
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

FilippoG
  • 329
  • 1
  • 2
  • 13
0
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);
Sergey
  • 1
  • 2
0
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());
}
mrded
  • 4,674
  • 2
  • 34
  • 36
0

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))
Vikas Gautam
  • 1,793
  • 22
  • 21
0

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;
}
b1919676
  • 92
  • 2
  • 8
0

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';
}
fp007
  • 412
  • 1
  • 4
  • 18
0

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)
radulle
  • 1,437
  • 13
  • 19
-1

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()));
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
-4

An Easier solution would be the following:

var d = new Date();
var n = d.getMilliseconds(); 
Kbdavis07
  • 1,012
  • 13
  • 24