Borislav Hadzhiev
Thu Jan 20 2022·2 min read
Photo by Linda Xu
To convert milliseconds to minutes and seconds:
60000
to convert them to minutes.10
.function padTo2Digits(num) { return num.toString().padStart(2, '0'); } function convertMsToMinutesSeconds(milliseconds) { const minutes = Math.floor(milliseconds / 60000); const seconds = Math.round((milliseconds % 60000) / 1000); return seconds === 60 ? `${minutes + 1}:00` : `${minutes}:${padTo2Digits(seconds)}`; } console.log(convertMsToMinutesSeconds(296900)); // 👉️ 4:57 console.log(convertMsToMinutesSeconds(296499)); // 👉️ 4:56 console.log(convertMsToMinutesSeconds(992000)); // 👉️ 16:32
We created a reusable function, which takes the milliseconds as a parameter and converts them to minutes and seconds.
padTo2Digits
function, which will take care of adding a leading zero if the seconds only contain a single digit (are less than 10
).We want to make sure the result does not alternate between single and double digit values depending on the seconds.
In our convertMsToTime
function, we:
60
, we have to add 1
minute to the minutes and set the seconds back to 0
.In any other case, we return the minutes and use the padTo2Digits
function to
pad the seconds to 2
digits if their value is less than 10
.
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(2)); // 👉️ '02' console.log(padTo2Digits(4)); // 👉️ '04' console.log(padTo2Digits(10)); // 👉️ '10'
You can also use this approach to pad the minutes, if you want the string to contain at least 2 digits for the minutes as well.
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } function convertMsToMinutesSeconds(milliseconds) { const minutes = Math.floor(milliseconds / 60000); const seconds = Math.round((milliseconds % 60000) / 1000); return seconds === 60 ? `${padTo2Digits(minutes + 1)}:00` : `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`; } console.log(convertMsToMinutesSeconds(296900)); // 👉️ 04:57 console.log(convertMsToMinutesSeconds(296499)); // 👉️ 04:56 console.log(convertMsToMinutesSeconds(992000)); // 👉️ 16:32
We used the padTo2Digits
to add a leading zero if the minutes are less than
10
.
The function returns a string that is formatted as mm:ss
, but you could tweak
this depending on your use case.