# Convert Milliseconds to Minutes and Seconds in JavaScript

Last updated: Jan 20, 2022

Photo from Unsplash

## Convert Milliseconds to Minutes and Seconds in JavaScript#

To convert milliseconds to minutes and seconds:

1. Divide the milliseconds by `60000` to convert them to minutes.
2. Convert the remainder to seconds.
3. Pad the seconds to two digits if the value is less than `10`.
index.js
```Copied!```function padTo2Digits(num) {
}

function convertMsToMinutesSeconds(milliseconds) {
const minutes = Math.floor(milliseconds / 60000);
const seconds = Math.round((milliseconds % 60000) / 1000);

return seconds === 60
? `\${minutes + 1}:00`
}

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.

The first thing we did is create a `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:

1. Converted the milliseconds to minutes.
2. Converted the remainder to seconds.
If the value for the seconds is equal to `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`.

index.js
```Copied!```function padTo2Digits(num) {
}

``````

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.

index.js
```Copied!```function padTo2Digits(num) {
}

function convertMsToMinutesSeconds(milliseconds) {
const minutes = Math.floor(milliseconds / 60000);
const seconds = Math.round((milliseconds % 60000) / 1000);

return seconds === 60
}

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
You can use the search field on my Home Page to filter through all of my articles.