Converting HH:MM:SS format to seconds in JavaScript
In this post we will give you information about Converting HH:MM:SS format to seconds in JavaScript. Hear we will give you detail about Converting HH:MM:SS format to seconds in JavaScriptAnd how to use it also give you demo for it if it is necessary.
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 stringconst arr = timeString.split(":"); // splitting the string by colonconst seconds = arr[0]*3600+arr[1]*60+(+arr[2]); // convertingconsole.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
Hope this code and post will helped you for implement Converting HH:MM:SS format to seconds in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs