How To Convert HH:MM:SS To Seconds Using Javascript

Convert HH:MM:SS to Seconds using JavaScript

This article shows you how to convert HH:MM:SS to seconds using Javascript. You will know the way to use the split() method and the multiplication and addition operations to convert it.

Convert HH:MM:SS to seconds using Javascript.

Use the split() method and the multiplication and addition operations

To convert HH:mm:SS format to seconds, first, we need to split the string into an array with a colon ‘:’. We will use the split() method to split it.

Then multiply the hour value in the array by 3600 and the minute value by 60. Finally, we add the value hours and minutes after converting with the original minute value to get seconds.

Code sample

function convertToSeconds(time){

    // Slicing the time string at the colons into an array including hours, minutes and seconds
    let timeArr = time.split(':');
 
    // Convert hours and minutes to seconds and add the total number of seconds
    let seconds = timeArr[0]*60*60 + timeArr[1]*60 + timeArr[2];
   
    console.log(seconds);
}
 
convertToSeconds('24:23:24');
convertToSeconds('18:32:05');

Output

8778024
6672005

We multiply hours by 3600 and minutes by 60 because 1 hour has 3600 seconds and 1 minute has 60 seconds.

Use the split() and Math.pow() method

The Math.pow(x, y) method has the function to calculate the power x to the power y (xy). The method will return the result of a mathematical exponent where x is the base and y is the exponent.

Syntax

Math.pow(x, y)

Parameters:

  • x: the base
  • y: the exponent

We also split the string into an array like the first way. Then reverse that array to get the new order of seconds, minutes, and hours.

Code sample:

let time1 = '15:20:40';
 
// Slicing time1 at the colons into an array including hours, minutes and seconds
let timeArr = time1.split(':');
 
// Reverse the timeArr array to seconds, minutes and hours
timeArr.reverse();
 
let seconds = 0;

// Convert to seconds by multiplying by 60 power i
for(let i = 0; i < timeArr.length; i++){
    seconds = seconds + timeArr[i] * Math.pow(60, i);
}
 
console.log(seconds);

Run the for loop on the array after inverting. The first second value corresponds to i = 0, the minute value corresponds to i = 1, and the hour value corresponds to i = 2. We will multiply the values ​​by 60 to the power of i and add up to the seconds.

Output

55240

Summary

Above, I showed you how to convert HH:MM:SS to seconds using Javascript. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *