Converting HH:MM:SS format to seconds in JavaScript
In this tutorial, we are going to learn about how to convert the "hh:mm:ss"
string format to seconds in JavaScript.
Consider, we have a following time string:
const timeString = "08:35:42";
Now, we need to convert the above format into seconds.
To convert a hh:mm:ss
format to seconds, first we need to split the string by colon :
and multiply the hour
value with 3600
and minutes value with 60
then we need to add everything to get the seconds.
Here is an example:
const timeString = "08:35:42"; // input string
const arr = timeString.split(":"); // splitting the string by colon
const seconds = arr[0]*3600+arr[1]*60+(+arr[2]); // converting
console.log(seconds);
Output:
30942
Note: In the above code we are multiplying hours with 3600 and minutes with 60 because 1 hour contains 3600 seconds, 1 minute contains 60 seconds.
We can also create our own reusable function like this to convert hh:mm:ss
to seconds.
function convertHMS(timeString){
const arr = timeString.split(":");
const seconds = arr[0]*3600+arr[1]*60+(+arr[2]);
return seconds;
}
console.log(convertHMS("08:35:42")); // 30942