Convert HH:MM:SS to seconds with JavaScript?

To convert HH:MM:SS to seconds with JavaScript, we will be using simple arithmetic operations like mltiplication and addition. We will be understanding this conversion with two example codes and their stepwise explanation.

In this article, we are given a time in HH:MM:SS format and our task is to convert HH:MM:SS to seconds with JavaScript.

Steps to Convert HH:MM:SS to Seconds

  • We have used two div to display the time and the result in seconds.
  • The time variable stores the time in HH:MM:SS format. Then we have used split() function to split hour, minutes and seconds by colon and stored it in realTime.
  • Then we have used index to access hours, minutes and seconds which was stored in realTime. We have multiplied hours by 60*60 and minutes by 60 to convert into seconds.
  • At the end, we have displayed the result by accessing the div with id result using getElementById() method and innerHTML.

Example 1

Here is a complete example code implementing above mentioned steps to convert HH:MM:SS to seconds with JavaScript.




    Converting Time to Seconds


    

Converting HH:MM:SS to seconds with JavaScript

Example 2

In this example, we are taking time as input from users in HH:MM:SS format. We have used text type input field and value property to get the time entered by user and a button that triggers toSec() function that converts time to seconds.




    Converting Time to Seconds


    

Converting HH:MM:SS to seconds with JavaScript

In this example, we are accepting time as user input to convert time to seconds.


Conclusion

In this article, we understood how to convert HH:MM:SS to seconds. We have provided two examples for converting time to seconds where, in first example a fixed time is given and in seconds example, time can be enterd by users.

Updated on: 2024-11-13T12:28:23+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements