How to Convert Seconds to Minutes and Seconds in JavaScript

Programmers often need to convert the time in different scales for different usages. One such important usage is the conversion of seconds into minutes. In this article, we will show how to convert seconds to minutes and seconds in javascript.

How to Convert Seconds to Minutes and Seconds

Before coding we need to know the following information:

  1. 60 seconds is equal to 1 minute.
  2. Conversely, 1 minute is equal to 60 seconds.

Algorithm

We can use the following algorithm to convert seconds to minutes in javascript:

  1. Divide the total seconds by 60. This will represent the number of minutes corresponding to the number of seconds.
  2. Here we apply the Math. floor() method to minutes to round down it.
  3. For calculating the remaining seconds, we will perform the modulo(%) of total seconds by 60.
  4. Last, we format minutes and seconds as MM:SS 

Example

let total_seconds = 345;


let minute = Math.floor(total_seconds/60);


let remaining_seconds = total_seconds % 60;


console.log(minute + " minute " + remaining_seconds + " seconds");

Output

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

Example 

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'));

Output

05:45

Conclusion

In this article, we have learned how to convert seconds to minutes in JavaScript. Having this concept is very important because it is a basic concept used in almost all programming fields whether it is blogging websites, subscription websites, crypto websites, etc.

Leave a Comment