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.