Convert Seconds To Minutes And Seconds In JavaScript

We will learn how to convert seconds to minutes and seconds in JavaScript with Math.floor() and % operator method. This fundamental skill is very helpful when you work with time in Javascript.

Convert seconds to minutes and seconds in JavaScript

Using Math.floor()

This function returns the number rounded down (The largest integer number which is not larger than the given number).

Syntax:

Math.floor(x)

Parameter:

• x: The float number to be floored (Rounded to the integer part).

You can use the Math.floor() function to get the result of a division of your seconds with 60 to get the number of minutes. After you have the minutes, you can multiply it with 60 and then minus it from the original seconds then you can get the seconds part.

let time = 123;
let minutes = Math.floor(time / 60);
let seconds = time - minutes * 60;

console.log("Minutes: " + minutes + ", seconds: " + seconds);

Output:

Minutes: 2, seconds: 3

Using modulus operator

The % operator is a binary operator which gives the result of the remainder.

Syntax:

a % b

You can convert your time (Which may be larger than 60) to the seconds (Which is less than 60) by using the % operator to get the remainder of the division by 60. Then you can get the minutes by minus the second you have found from the original time then divide it with 60.

let time = 123;
let seconds = time % 60;
let minutes = (time - seconds) / 60;

console.log("Minutes: " + minutes + ", seconds: " + seconds);

Output:

Minutes: 2, seconds: 3

Using Math.floor() and modulus operator

The first function acts on a float number, while the rest is a binary operator which gives the result of the remainder.

You can use the Math.floor() function to get the result of a division of your time with 60 to get the number of minutes. Then to get the seconds left you need to use the % operator to get the remainder of the division by 60. The seconds returned will always be smaller than 60.

let time = 123;
let minutes = Math.floor(time / 60);
let seconds = time % 60;

console.log("Minutes: " + minutes + ", seconds: " + seconds);

Output:

Minutes: 2, seconds: 3

The above example points out that the original time we have in seconds is 123 seconds; after converting it to minutes and seconds, we have 2 minutes and 3 seconds. This method is actually used by most programmers. It is based on the two approaches we introduced in this tutorial.

Summary

We have learned how to convert seconds to minutes and seconds in JavaScript using three different approaches. It would be necessary to remember that the third approach is based on the two others. By using our instructions in this tutorial and other ones, you can convert your time to any unit.

Maybe you are interested: