78

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
2
  • 3
    Lets see here 1 second = 1000ms so... Commented Mar 19, 2012 at 0:02
  • 1
    As far as I'm concerned 1000 ms's make a second, so how can you have a 4-digit number in the ms area?
    – inhan
    Commented Mar 19, 2012 at 0:07

19 Answers 19

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

3
  • This algorithm fails when the milliseconds are less than .1, e.g. 55018 should be "55.018" but it yields "55.18" Commented Jan 2, 2017 at 22:52
  • This also fails if the ms value is fractional. Perhaps add s = Math.round(s) near the beginning to sort that out.
    – Blorf
    Commented May 28, 2019 at 14:46
  • best solution for me..works fine in typescritp with ionic5 Commented Sep 23, 2020 at 15:19
80

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"

6
  • @Ziarno Not sure how React Native works but if it uses modern JS processor on behind, this code should be executed.
    – VisioN
    Commented Jan 23, 2017 at 12:44
  • hmm you're right, it does work. Must have had a different bug, sorry
    – Ziarno
    Commented Jan 24, 2017 at 12:32
  • This works for ms less than 24h. Every 24h, hours will start from 0 again.
    – haiiaaa
    Commented Mar 31, 2017 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
    Commented Mar 31, 2017 at 12:16
  • Thanks it helper me Commented Jul 16, 2017 at 14:29
27
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;
}
5
  • 2
    Using Math.floor for seconds and minutes might be a good idea.
    – inhan
    Commented Mar 19, 2012 at 0:18
  • Math.floor is not required for milliseconds.
    – RobG
    Commented Mar 19, 2012 at 0:33
  • @RobG It was not about milliseconds, it was about the 2 lines in Richard's code.
    – inhan
    Commented Mar 19, 2012 at 1:50
  • @inhan—agreed, I gave you +1. But Richard had a Math.floor for ms too that has now been removed. :-)
    – RobG
    Commented Mar 19, 2012 at 2:49
  • Who Hoo! This post made my reputation OVER NINE THOUSAND! Commented Mar 21, 2012 at 16:08
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/

2
  • 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. Commented Sep 22, 2014 at 15:20
  • @RajshekarReddy I fixed that issue by using the UTC getters.
    – sissonb
    Commented Jun 3, 2017 at 2:05
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;
}
0
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}}
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}`
}
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;
}
1
  • Actually bad idea since it adds hours difference from UTC - not cool for time duration Commented Feb 28, 2021 at 14:12
1

This worked for me:

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

JSFiddle

1
  • 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
    Commented Jun 1, 2016 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 "";
   }
0
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

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

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

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

An Easier solution would be the following:

var d = new Date();
var n = d.getMilliseconds(); 
1
  • That's not what OP wants.
    – Artjom B.
    Commented Jun 4, 2015 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.