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.