Convert Seconds to Minutes and Seconds in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

Convert Seconds to Minutes and Seconds in JavaScript #

To convert seconds to minutes and seconds:

  1. Get the number of full minutes by dividing the seconds by 60.
  2. Get the remainder of the seconds.
  3. Optionally, format the minutes and seconds as mm:ss.
index.js
const totalSeconds = 565; // 👇️ get number of full minutes const minutes = Math.floor(totalSeconds / 60); // 👇️ get remainder of seconds const seconds = totalSeconds % 60; function padTo2Digits(num) { return num.toString().padStart(2, '0'); } // ✅ format as MM:SS const result = `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`; console.log(result); // 👉️ "09:25"

The first step is to get the number of full minutes by dividing the seconds by 60 and rounding the result down.

The Math.floor function rounds a number down if the number has a decimal, otherwise it returns the number as is.

index.js
console.log(Math.floor(9.99)); // 👉️ 9 console.log(Math.floor(9.01)); // 👉️ 9 console.log(Math.floor(9)); // 👉️ 9
This ensures that we don't get values with a decimal, e.g. 9.416 for the minutes. If the value has a decimal, we want to show the seconds and hide the decimal.

We used the modulo (%) operator to get the remainder of seconds.

index.js
const totalSeconds = 565; // 👇️ get remainder of seconds const seconds = totalSeconds % 60; console.log(seconds); // 👉️ 25

When we divide totalSeconds by 60, we get a remainder of 25 seconds.

In other words, once we subtract all the full minutes from totalSeconds, we have 25 seconds left.

The next step is to format the minutes and seconds as mm:ss, e.g. 05:45.

Our padTo2Digits function, takes care of adding a leading zero if the minutes or seconds only contain a single digit (are less than 10).

index.js
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(1)); // 👉️ '01' console.log(padTo2Digits(5)); // 👉️ '05' console.log(padTo2Digits(10)); // 👉️ '10'

We want to make sure the result doesn't alternate between single and double digit values depending on the minutes and seconds.

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