Borislav Hadzhiev
Thu Jan 20 2022·2 min read
Photo by Cristina Gottardi
To convert milliseconds to hours, minutes, seconds:
1000
to get the seconds.60
to get the minutes.60
to get the hours.10
to format them
consistently.// ✅ You can use a Quick one-liner hack const ms = 54000000; console.log(new Date(ms).toISOString().slice(11, 19)); // 👉️ 15:00:00 // ✅ Or create a reusable function function padTo2Digits(num) { return num.toString().padStart(2, '0'); } function convertMsToTime(milliseconds) { let seconds = Math.floor(milliseconds / 1000); let minutes = Math.floor(seconds / 60); let hours = Math.floor(minutes / 60); seconds = seconds % 60; minutes = minutes % 60; // 👇️ If you don't want to roll hours over, e.g. 24 to 00 // 👇️ comment (or remove) the line below // commenting next line gets you `24:00:00` instead of `00:00:00` // or `36:15:31` instead of `12:15:31`, etc. hours = hours % 24; return `${padTo2Digits(hours)}:${padTo2Digits(minutes)}:${padTo2Digits( seconds, )}`; } console.log(convertMsToTime(54000000)); // 👉️ 15:00:00 (15 hours) console.log(convertMsToTime(86400000)); // 👉️ 00:00:00 (24 hours) console.log(convertMsToTime(36900000)); // 👉️ 10:15:00 (10 hours, 15 minutes) console.log(convertMsToTime(15305000)); // 👉️ 04:15:05 (4 hours, 15 minutes, 5 seconds)
We created a reusable function, which takes milliseconds as a parameter and
returns the hours, minutes and seconds representation, formatted as hh:mm:ss
.
padTo2Digits
function, which will take care of adding a leading zero if the hours, minutes or seconds only contain a single digit (are less than 10
).function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(3)); // 👉️ '03' console.log(padTo2Digits(6)); // 👉️ '06' console.log(padTo2Digits(10)); // 👉️ '10'
We want to make sure the result does not alternate between single and double digit values depending on the hour, minutes and seconds.
In our convertMsToTime
function, we:
1000
.60
.60
.0
if, for example, the
user passed 86400000
as the milliseconds, which is equivalent to 24
hours.24
, e.g. if the milliseconds are 36 hours, the hours = hours % 24
line set the hours to 12
. Depending on your use case, you might not want to roll the hours over.You can comment out the hours = hours % 24
line to not roll the hours over.
The last step is to format the values for the hours, minutes and seconds in a way that suits your use case.
hh:mm:ss
in the example, by adding a leading zero if the value is less than 10
, however you can tweak the return value of the function depending on your use case.