Borislav Hadzhiev
Thu Jan 20 2022·2 min read
Photo by Octavian Rosca
To convert seconds to minutes and seconds:
60
.mm:ss
.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.
console.log(Math.floor(9.99)); // 👉️ 9 console.log(Math.floor(9.01)); // 👉️ 9 console.log(Math.floor(9)); // 👉️ 9
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.
const totalSeconds = 565; // 👇️ get remainder of seconds const seconds = totalSeconds % 60; console.log(seconds); // 👉️ 25
This means that 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 as 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
).
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 does not alternate between single and double digit values depending on the minutes and seconds.