Categories
JavaScript Answers

How to convert HH:MM:SS string to seconds only in JavaScript?

Spread the love

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

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

How to convert HH:MM:SS string to seconds only in JavaScript?

To convert HH:MM:SS string to seconds only in JavaScript, we can split the time string.

And then we convert the hours and minutes to seconds and add them to the seconds.

For instance, we write

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

to use hms.split(":") to split the string by the colons.

And then we convert the hours string to seconds with +hours * 60 * 60.

+ converts hours to a number.

Likewise, we convert minutes to seconds with +minutes * 60.

Then we add them both to seconds.

Conclusion

To convert HH:MM:SS string to seconds only in JavaScript, we can split the time string.

And then we convert the hours and minutes to seconds and add them to the 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 *