Categories
JavaScript Answers

How to Convert HH:MM:SS Time String to Seconds Only in JavaScript?

Spread the love

Sometimes, we want to convert a HH:MM:SS time string to seconds only in JavaScript.

In this article, we’ll look at how to convert a HH:MM:SS time string to seconds only in JavaScript.

Convert HH:MM:SS Time String to Seconds Only in JavaScript

We can convert a HH:MM:SS time string to seconds only in JavaScript by converting the hours and minutes to seconds.

And then add the converted values to the seconds’ portion of the time.

For instance, we can write:

const hms = '02:04:33';
const [hours, minutes, seconds] = hms.split(':');
const totalSeconds = (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds);
console.log(totalSeconds);

We have the hms string in HH:MM:SS format.

Then we split by the colons with the split method.

Next, we get the hours and convert it to a number with the + operator and multiply by 60* 60 to convert that to seconds.

Then we add that to the minutes converted to a number and multiplied by 60 to convert the minutes to seconds.

And then we add both to the seconds to get the totalSeconds .

As a result, totalSeconds is 7473.

Conclusion

We can convert a HH:MM:SS time string to seconds only in JavaScript by converting the hours and minutes to seconds.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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