Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a time as a number of milliseconds and I want to convert it to a HH:MM:SS format. It should wrap around, with milliseconds = 86400000 I want to get 00:00:00.

like image 269
cheliyan Avatar asked Oct 31 '13 07:10

cheliyan


People also ask

How do you convert milliseconds to minutes and seconds?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60). The print output from Milliseconds to minutes and seconds.

How do you convert milliseconds to time?

To convert a second measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the seconds multiplied by 1,000.


2 Answers

How about creating a function like this:

function msToTime(duration) {   var milliseconds = Math.floor((duration % 1000) / 100),     seconds = Math.floor((duration / 1000) % 60),     minutes = Math.floor((duration / (1000 * 60)) % 60),     hours = Math.floor((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; } console.log(msToTime(300000))
like image 74
Dusht Avatar answered Sep 22 '22 19:09

Dusht


To Convert time in millisecond to human readable format.

function msToTime(ms) {   let seconds = (ms / 1000).toFixed(1);   let minutes = (ms / (1000 * 60)).toFixed(1);   let hours = (ms / (1000 * 60 * 60)).toFixed(1);   let days = (ms / (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" }  console.log(msToTime(1000)) console.log(msToTime(10000)) console.log(msToTime(300000)) console.log(msToTime(3600000)) console.log(msToTime(86400000))

"Out Put Sample"

like image 23
Nofi Avatar answered Sep 19 '22 19:09

Nofi