Convert seconds to minutes and seconds in JavaScript:
- The entire minutes are obtained by dividing the seconds by 60.
- Gets the remaining seconds.
- Alternatively, set the format of minutes and seconds to mm:ss.
const totalSeconds = 565; // ?️ Get the full minutesconst minutes = (totalSeconds / 60); // ?️ Get the remaining secondsconst seconds = totalSeconds % 60; function padTo2Digits(num) { return ().padStart(2, '0'); } // ✅ Formatted as MM:SSconst result = `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`; (result); // ?️ "09:25"
The first step is to get the full number of minutes by dividing the seconds by 60 and rounding the result down.
If the number has a decimal, the function rounds the number down, otherwise the number is returned as is.
((9.99)); // ?️ 9 ((9.01)); // ?️ 9 ((9)); // ?️ 9
We use the modulo % operator to get the remaining seconds.
const totalSeconds = 565; // ?️ get remainder of seconds const seconds = totalSeconds % 60; (seconds); // ?️ 25
When we divide totalSeconds by 60, we get the remainder of 25 seconds.
The next step is to format the minutes and seconds as mm:ss, for example 05:45.
If minutes or seconds contain only one number (less than 10), our padTo2Digits function is responsible for adding leading zeros.
function padTo2Digits(num) { return ().padStart(2, '0'); } (padTo2Digits(1)); // ?️ '01' (padTo2Digits(5)); // ?️ '05' (padTo2Digits(10)); // ?️ '10'
We want to make sure that the results do not alternate between one-digit and two-digit values based on minutes and seconds.
This is the end of this article about converting seconds to minutes and seconds in JavaScript. For more related content on converting seconds to minutes and seconds, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!