Convert seconds to minutes and seconds (mm:ss) using JavaScript


In this tutorial, we will learn how to convert seconds into minutes and seconds using JavaScript.

Before we code the function we have to know that is 1min = 60seconds.

So mathematically to find the minutes from seconds, we have to divide the given value by 60.

For example, to find the minutes from 120sec we have to do this.

120 / 60 (1 min = 60sec)
= 2 // answer is 2 minutes

So with this basic concept, we can code a Javascript function that will take seconds as a parameter and return us the minutes and seconds (mm:ss) equivalent to it.

Convert seconds into minutes and seconds using vanilla JavaScript

To convert seconds into minutes and seconds we have to follow these three steps in our code:

  1. Extract minutes from the seconds (given value) by dividing it by 60.
  2. Get the remaining seconds from the reminder using % mod (Division Remainder)
  3. Return the converted value.

Let's see it in code

function getMinAndSec(seconds){
    const min = seconds / 60;
    const secs = seconds%60;
    return `${min} minutes and ${secs} seconds`;
}


console.log(getMinAndSec(120))

Output:

2 minutes and 0 seconds

However, if we pass 140 sec to the function we get

getMinAndSec(140) // 2.3333333333333335 minutes and 20 seconds

We get values in decimals. To solve this issue we have to use Math.floor() function.

The Math. floor() return the largest integer that is less than or equal to a given number.

function getMinAndSec(seconds){
    const min = Math.floor(seconds / 60); 
    const secs = seconds%60;
    return `${min} minutes and ${secs} seconds`;
}

console.log(getMinAndSec(140)) // 2 minutes and 20 seconds

Here, we have divided the given value, 140 by 60 and we get 2.333 from which we took the floor number 2 as the minutes.

And the remainder of the number (140%60) is 20 which is the seconds.

Format time to mm:ss in JavaScript

If you want the output in the mm:ss format we can use the toString() and padStart() methods in JavaScript.

The toString() method converts a number to a string in JavaScript.

The padStart() method is used to pad one string with another till the resulting string reaches the given length.

Syntax:

padStart(targetLength, padString)

targetLength: final length of the string.

padString: string to be padded.

So, let code the function to convert seconds into minutes and seconds in mm:ss format:

function getMinAndSec(seconds){
    const min = Math.floor(seconds / 60);
    const secs = seconds%60;
    return min.toString().padStart(2, '0')+":"+secs.toString().padStart(2, '0');
}

console.log(getMinAndSec(140))

Ouput:

02:20

In the above code, the padStart targeted string length is 2 to get the results in 2 digits.

Related articles:

JavaScript - Convert Days to Seconds


💾 Recommended Articles