How to Convert Seconds to Minutes and Seconds
Before coding we need to know the following information:
- 60 seconds is equal to 1 minute.
- Conversely, 1 minute is equal to 60 seconds.
- Divide the total seconds by 60. This will represent the number of minutes corresponding to the number of seconds.
- Here we apply the Math. floor() method to minutes to round down it.
- For calculating the remaining seconds, we will perform the modulo(%) of total seconds by 60.
- Last, we format minutes and seconds as MM:SS
let total_seconds = 345; let minute = Math.floor(total_seconds/60); let remaining_seconds = total_seconds % 60; console.log(minute + " minute " + remaining_seconds + " seconds");
5 minute 45 seconds
When you divide total_seconds by 60, we get 5 minutes. Remainder here is 45 which is the remaining seconds.
We are going to use toString() and padStart() methods to format the minutes and seconds as MM:SS .
First, we use the toString() method to convert our number elements to a string and then apply padStart() method which makes it a 2-digit string with the starting digit as 0
let total_seconds = 345; let minute = Math.floor(total_seconds/60); let remaining_seconds = total_seconds % 60; console.log(minute.toString().padStart(2, '0')+":"+remaining_seconds.toString().padStart(2, '0'));