[javascript] How to convert time milliseconds to hours, min, sec format in JavaScript?

I have the time as milliseconds, but I want the time after conversion like 00:00:00.

Ex: In milliseconds=86400000. I want how many hours in that milliseconds like, 00:00:00

How to get it in JavaScript?

This question is related to javascript datetime milliseconds

The answer is


To Convert time in millisecond to human readable format.

 function timeConversion(millisec) {

        var seconds = (millisec / 1000).toFixed(1);

        var minutes = (millisec / (1000 * 60)).toFixed(1);

        var hours = (millisec / (1000 * 60 * 60)).toFixed(1);

        var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);

        if (seconds < 60) {
            return seconds + " Sec";
        } else if (minutes < 60) {
            return minutes + " Min";
        } else if (hours < 24) {
            return hours + " Hrs";
        } else {
            return days + " Days"
        }
    }

"Out Put Sample"


Extending on @Rick's answer, I prefer something like this:

function msToReadableTime(time){
  const second = 1000;
  const minute = second * 60;
  const hour = minute * 60;

  let hours = Math.floor(time / hour % 24);
  let minutes = Math.floor(time / minute % 60);
  let seconds = Math.floor(time / second % 60);
 

  return hours + ':' + minutes + ":" + seconds;
}

This solution uses one function to split milliseconds into a parts object, and another function to format the parts object.

I created 2 format functions, one as you requested, and another that prints a friendly string and considering singular/plural, and includes an option to show milliseconds.

_x000D_
_x000D_
function parseDuration(duration) {_x000D_
  let remain = duration_x000D_
_x000D_
  let days = Math.floor(remain / (1000 * 60 * 60 * 24))_x000D_
  remain = remain % (1000 * 60 * 60 * 24)_x000D_
_x000D_
  let hours = Math.floor(remain / (1000 * 60 * 60))_x000D_
  remain = remain % (1000 * 60 * 60)_x000D_
_x000D_
  let minutes = Math.floor(remain / (1000 * 60))_x000D_
  remain = remain % (1000 * 60)_x000D_
_x000D_
  let seconds = Math.floor(remain / (1000))_x000D_
  remain = remain % (1000)_x000D_
_x000D_
  let milliseconds = remain_x000D_
_x000D_
  return {_x000D_
    days,_x000D_
    hours,_x000D_
    minutes,_x000D_
    seconds,_x000D_
    milliseconds_x000D_
  };_x000D_
}_x000D_
_x000D_
function formatTime(o, useMilli = false) {_x000D_
  let parts = []_x000D_
  if (o.days) {_x000D_
    let ret = o.days + ' day'_x000D_
    if (o.days !== 1) {_x000D_
      ret += 's'_x000D_
    }_x000D_
    parts.push(ret)_x000D_
  }_x000D_
  if (o.hours) {_x000D_
    let ret = o.hours + ' hour'_x000D_
    if (o.hours !== 1) {_x000D_
      ret += 's'_x000D_
    }_x000D_
    parts.push(ret)_x000D_
  }_x000D_
  if (o.minutes) {_x000D_
    let ret = o.minutes + ' minute'_x000D_
    if (o.minutes !== 1) {_x000D_
      ret += 's'_x000D_
    }_x000D_
    parts.push(ret)_x000D_
_x000D_
  }_x000D_
  if (o.seconds) {_x000D_
    let ret = o.seconds + ' second'_x000D_
    if (o.seconds !== 1) {_x000D_
      ret += 's'_x000D_
    }_x000D_
    parts.push(ret)_x000D_
  }_x000D_
  if (useMilli && o.milliseconds) {_x000D_
    let ret = o.milliseconds + ' millisecond'_x000D_
    if (o.milliseconds !== 1) {_x000D_
      ret += 's'_x000D_
    }_x000D_
    parts.push(ret)_x000D_
  }_x000D_
  if (parts.length === 0) {_x000D_
    return 'instantly'_x000D_
  } else {_x000D_
    return parts.join(' ')_x000D_
  }_x000D_
}_x000D_
_x000D_
function formatTimeHMS(o) {_x000D_
  let hours = o.hours.toString()_x000D_
  if (hours.length === 1) hours = '0' + hours_x000D_
_x000D_
  let minutes = o.minutes.toString()_x000D_
  if (minutes.length === 1) minutes = '0' + minutes_x000D_
_x000D_
  let seconds = o.seconds.toString()_x000D_
  if (seconds.length === 1) seconds = '0' + seconds_x000D_
_x000D_
  return hours + ":" + minutes + ":" + seconds_x000D_
}_x000D_
_x000D_
function formatDurationHMS(duration) {_x000D_
  let time = parseDuration(duration)_x000D_
  return formatTimeHMS(time)_x000D_
}_x000D_
_x000D_
function formatDuration(duration, useMilli = false) {_x000D_
  let time = parseDuration(duration)_x000D_
  return formatTime(time, useMilli)_x000D_
}_x000D_
_x000D_
_x000D_
console.log(formatDurationHMS(57742343234))_x000D_
_x000D_
console.log(formatDuration(57742343234))_x000D_
console.log(formatDuration(5423401000))_x000D_
console.log(formatDuration(500))_x000D_
console.log(formatDuration(500, true))_x000D_
console.log(formatDuration(1000 * 30))_x000D_
console.log(formatDuration(1000 * 60 * 30))_x000D_
console.log(formatDuration(1000 * 60 * 60 * 12))_x000D_
console.log(formatDuration(1000 * 60 * 60 * 1))
_x000D_
_x000D_
_x000D_


How about doing this by creating a function in javascript as shown below:

_x000D_
_x000D_
function msToTime(duration) {_x000D_
  var milliseconds = parseInt((duration % 1000) / 100),_x000D_
    seconds = Math.floor((duration / 1000) % 60),_x000D_
    minutes = Math.floor((duration / (1000 * 60)) % 60),_x000D_
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);_x000D_
_x000D_
  hours = (hours < 10) ? "0" + hours : hours;_x000D_
  minutes = (minutes < 10) ? "0" + minutes : minutes;_x000D_
  seconds = (seconds < 10) ? "0" + seconds : seconds;_x000D_
_x000D_
  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;_x000D_
}_x000D_
console.log(msToTime(300000))
_x000D_
_x000D_
_x000D_


If you're using typescript, this could be a good thing for you

enum ETime {
  Seconds = 1000,
  Minutes = 60000,
  Hours = 3600000,
  SecInMin = 60,
  MinInHours = 60,
  HoursMod = 24,
  timeMin = 10,
}

interface ITime {
  millis: number
  modulo: number
}

const Times = {
  seconds: {
    millis: ETime.Seconds,
    modulo: ETime.SecInMin,
  },
  minutes: {
    millis: ETime.Minutes,
    modulo: ETime.MinInHours,
  },
  hours: {
    millis: ETime.Hours,
    modulo: ETime.HoursMod,
  },
}

const dots: string = ":"

const msToTime = (duration: number, needHours: boolean = true): string => {
  const getCorrectTime = (divider: ITime): string => {
    const timeStr: number = Math.floor(
      (duration / divider.millis) % divider.modulo,
    )

    return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
  }

  return (
    (needHours ? getCorrectTime(Times.hours) + dots : "") +
    getCorrectTime(Times.minutes) +
    dots +
    getCorrectTime(Times.seconds)
  )
}

I works for me as i get milliseconds=1592380675409 using javascript method getTime() which returns the number of milliseconds between midnight of January 1, 1970 and the specified date.

var d = new Date();//Wed Jun 17 2020 13:27:55 GMT+0530 (India Standard Time)
var n = d.getTime();//1592380675409 this value is store somewhere

//function call 
console.log(convertMillisecToHrMinSec(1592380675409));

var convertMillisecToHrMinSec = (time) => {
  let date = new Date(time);
  let hr = date.getHours();
  let min = date.getMinutes();
  let sec = date.getSeconds();

  hr = (hr < 10) ? "0"+ hr : hr;
  min = (min < 10) ? "0"+ min : min;
  sec = (sec < 10) ? "0"+ sec : sec;

  return hr + ':' + min + ":" + sec;//01:27:55
}

Worked for me

msToTime(milliseconds) {
    //Get hours from milliseconds
    var hours = milliseconds / (1000*60*60);
    var absoluteHours = Math.floor(hours);
    var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;

    //Get remainder from hours and convert to minutes
    var minutes = (hours - absoluteHours) * 60;
    var absoluteMinutes = Math.floor(minutes);
    var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;

    //Get remainder from minutes and convert to seconds
    var seconds = (minutes - absoluteMinutes) * 60;
    var absoluteSeconds = Math.floor(seconds);
    var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;

    return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
}

In my implementation I used Moment.js:

export default (value) => 
  const duration = moment.duration(value);

  const milliseconds = duration.milliseconds();
  const seconds = duration.seconds();
  const minutes = duration.minutes();
  const hours = duration.hours();
  const day = duration.days();

  const sDay = `${day}d `;
  const sHours = (hours < 10) ? `0${hours}h ` : `${hours}h `;
  const sMinutes = (minutes < 10) ? `0${minutes}' ` : `${minutes}' `;
  const sSeconds = (seconds < 10) ? `0${seconds}" ` : `${seconds}" `;
  const sMilliseconds = `${milliseconds}ms`;

  ...
}

Once got the strings, I composed them as I want.


Here is my solution

let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);

// to get time format 00:00:00

s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`


console.log(`${s}:${m}:${h}`);

I had the same problem, this is what I ended up doing:

_x000D_
_x000D_
function parseMillisecondsIntoReadableTime(milliseconds){_x000D_
  //Get hours from milliseconds_x000D_
  var hours = milliseconds / (1000*60*60);_x000D_
  var absoluteHours = Math.floor(hours);_x000D_
  var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;_x000D_
_x000D_
  //Get remainder from hours and convert to minutes_x000D_
  var minutes = (hours - absoluteHours) * 60;_x000D_
  var absoluteMinutes = Math.floor(minutes);_x000D_
  var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;_x000D_
_x000D_
  //Get remainder from minutes and convert to seconds_x000D_
  var seconds = (minutes - absoluteMinutes) * 60;_x000D_
  var absoluteSeconds = Math.floor(seconds);_x000D_
  var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;_x000D_
_x000D_
_x000D_
  return h + ':' + m + ':' + s;_x000D_
}_x000D_
_x000D_
_x000D_
var time = parseMillisecondsIntoReadableTime(86400000);_x000D_
_x000D_
alert(time);
_x000D_
_x000D_
_x000D_


Sorry, late to the party. The accepted answer did not cut it for me, so I wrote it myself.

Output:

2h 59s
1h 59m
1h
1h 59s
59m 59s
59s

Code (Typescript):

function timeConversion(duration: number) {
  const portions: string[] = [];

  const msInHour = 1000 * 60 * 60;
  const hours = Math.trunc(duration / msInHour);
  if (hours > 0) {
    portions.push(hours + 'h');
    duration = duration - (hours * msInHour);
  }

  const msInMinute = 1000 * 60;
  const minutes = Math.trunc(duration / msInMinute);
  if (minutes > 0) {
    portions.push(minutes + 'm');
    duration = duration - (minutes * msInMinute);
  }

  const seconds = Math.trunc(duration / 1000);
  if (seconds > 0) {
    portions.push(seconds + 's');
  }

  return portions.join(' ');
}

console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)              ));
console.log(timeConversion((60 * 60 * 1000)                                 ));
console.log(timeConversion((60 * 60 * 1000)                    + (59 * 1000)));
console.log(timeConversion(                   (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion(                                      (59 * 1000)));

Based on @Chand answer. This is the implementation in Typescript. A bit safer than coercing types in JS. If you remove the type annotation should be valid JS. Also using new string functions to normalise the time.

function displayTime(millisec: number) {
 const normalizeTime = (time: string): string => (time.length === 1) ? time.padStart(2, '0') : time;

 let seconds: string = (millisec / 1000).toFixed(0);
 let minutes: string = Math.floor(parseInt(seconds) / 60).toString();
 let hours: string = '';

 if (parseInt(minutes) > 59) {
   hours = normalizeTime(Math.floor(parseInt(minutes) / 60).toString());
   minutes = normalizeTime((parseInt(minutes) - (parseInt(hours) * 60)).toString());
 }
 seconds = normalizeTime(Math.floor(parseInt(seconds) % 60).toString());

 if (hours !== '') {
    return `${hours}:${minutes}:${seconds}`;
 }
   return `${minutes}:${seconds}`;
}

Human-readable code for human-readable output and you can extend this to light years or nanoseconds or what have you very intuitively. Obviously you'd want to convert this to a function and re-use some of those intermediate modulo calls.

second = 1000 
minute = second * 60
hour = minute * 60 
day = hour * 24

test = 3 * day + 2 * hour + 11 * minute + 58 * second

console.log(Math.floor(test / day))
console.log(Math.floor(test % day / hour))
console.log(Math.floor(test % day % hour / minute))
console.log(Math.floor(test % day % hour % minute / second))

The above snippets don't work for cases with more than 1 day (They are simply ignored).

For this you can use:

function convertMS(ms) {
    var d, h, m, s;
    s = Math.floor(ms / 1000);
    m = Math.floor(s / 60);
    s = s % 60;
    h = Math.floor(m / 60);
    m = m % 60;
    d = Math.floor(h / 24);
    h = h % 24;
    h += d * 24;
    return h + ':' + m + ':' + s;
}

enter image description here

Thanks to https://gist.github.com/remino/1563878


I needed time only up to one day, 24h, this was my take:

_x000D_
_x000D_
const milliseconds = 5680000;_x000D_
_x000D_
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);_x000D_
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);_x000D_
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);_x000D_
_x000D_
const time = `${hours}:${minutes}:${seconds}`_x000D_
console.log(time);
_x000D_
_x000D_
_x000D_

you could get days this way as well if needed.


my solution

var sunriseMills = 1517573074000;         // sunrise in NewYork on Feb 3, 2018  - UTC time
var offsetCityMills = -5 * 3600 * 1000;   // NewYork delay to UTC 
var offsetDeviceMills =  new Date().getTimezoneOffset() * 60 * 1000 ;  // eg. I live in Romania (UTC+2) >> getTimezoneOffset() = 120

var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills) 
    .toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });

textTime will become '7.04 AM'


This one returns time like youtube videos

    function getYoutubeLikeToDisplay(millisec) {
        var seconds = (millisec / 1000).toFixed(0);
        var minutes = Math.floor(seconds / 60);
        var hours = "";
        if (minutes > 59) {
            hours = Math.floor(minutes / 60);
            hours = (hours >= 10) ? hours : "0" + hours;
            minutes = minutes - (hours * 60);
            minutes = (minutes >= 10) ? minutes : "0" + minutes;
        }

        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        if (hours != "") {
            return hours + ":" + minutes + ":" + seconds;
        }
        return minutes + ":" + seconds;
    }

Output:

  • getYoutubeLikeToDisplay(129900) = "2:10"
  • getYoutubeLikeToDisplay(1229900) = "20:30"
  • getYoutubeLikeToDisplay(21229900) = "05:53:50"

// The following is written in Typescript, should be easy to translate to JS

function humanReadableDuration(msDuration: int): string {
    const h = Math.floor(msDuration / 1000 / 60 / 60);
    const m = Math.floor((msDuration / 1000 / 60 / 60 - h) * 60);
    const s = Math.floor(((msDuration / 1000 / 60 / 60 - h) * 60 - m) * 60);

    // To get time format 00:00:00
    const seconds: string = s < 10 ? `0${s}` : `${s}`;
    const minutes: string = m < 10 ? `0${m}` : `${m}`;
    const hours: string = h < 10 ? `0${h}` : `${h}`;

    return `${hours}h ${minutes}m ${seconds}s`;
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to milliseconds

Timestamp with a millisecond precision: How to save them in MySQL How to get milliseconds from LocalDateTime in Java 8 Converting milliseconds to minutes and seconds with Javascript How to convert time milliseconds to hours, min, sec format in JavaScript? Getting date format m-d-Y H:i:s.u from milliseconds Get DateTime.Now with milliseconds precision How to convert milliseconds to seconds with precision How to convert a string Date to long millseconds How can I get the count of milliseconds since midnight for the current? milliseconds to days