How to Convert Seconds to Minutes and Seconds in JavaScript

Here are the ways to convert seconds into minutes and seconds in JavaScript:

  1. Divide the total seconds by 60 and use the modulus operator.
  2. Using the Bitwise Double Not (~~) Operator

Method 1: Divide the total seconds by 60 and use the modulus operator

Divide the total seconds by 60 to get the whole minute. Use the modulus operator (%) to get the remainder, the leftover seconds.

function secondsToMinutesAndSeconds(totalSeconds) {
  var minutes = Math.floor(totalSeconds / 60);
  var seconds = totalSeconds % 60;

  return {
    minutes: minutes,
    seconds: seconds
  };
}

// Example usage:
var result = secondsToMinutesAndSeconds(150);
console.log(result.minutes + " minutes and " + result.seconds + " seconds");

Output

2 minutes and 30 seconds

Method 2: Using the Bitwise Double Not (~~) Operator

Suppose you would like to use the bitwise double NOT (~~) operator to convert seconds to minutes in JavaScript. In that case, you can do so by first dividing the number of seconds by 60 (to get the minutes as a floating-point number) and then using ~~ to truncate the decimal portion of the result.

Example

function secondsToWholeMinutes(totalSeconds) {
  return ~~(totalSeconds / 60);
}

// Example usage:
var totalSeconds = 150;
console.log(secondsToWholeMinutes(totalSeconds) + " minutes");

Output

2 minutes

Convert seconds to HH:mm:ss

To convert seconds to the HH:mm:ss format in JavaScript, you can follow these steps:

  1. Divide the total seconds by 3600 to get the number of hours.
  2. Take the remainder from the above step and divide by 60 to get the number of minutes.
  3. The remainder of the previous step will be the number of seconds.
  4. Format each value to ensure it has at least two digits (e.g., 01 instead of 1).

Example

function secondsToHHMMSS(totalSeconds) {
  var hours = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // Padding the values to ensure they are two digits
  if (hours < 10) { hours = "0" + hours; }
  if (minutes < 10) { minutes = "0" + minutes; }
  if (seconds < 10) { seconds = "0" + seconds; }

  return hours + ':' + minutes + ':' + seconds;
}

// Example usage:
var totalSeconds = 3665;
console.log(secondsToHHMMSS(totalSeconds));

Output

01:01:05

That’s it!

Related posts

How to Get Time in 12 Hour Format in JavaScript

How to Get All Dates in a Month Using JavaScript

How to Get First and Last Day of Current Month in JavaScript

Leave a Comment