Convert HH:MM:SS to Seconds using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 20, 2022

banner

Photo from Unsplash

Convert HH:MM:SS to Seconds using JavaScript #

To convert hh:mm:ss to seconds:

  1. Convert the hours to seconds, by multiplying by 60 twice.
  2. Convert the minutes to seconds by multiplying by 60.
  3. Sum the results for the hours and minutes with the seconds to get the final value.
index.js
const str = '09:30:16'; const [hours, minutes, seconds] = str.split(':'); function convertToSeconds(hours, minutes, seconds) { return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds); } console.log(convertToSeconds(hours, minutes, seconds)); // 👉️ 34216
We created a reusable function, which takes hours, minutes and seconds as parameters and converts them to seconds.

The string in the example is formatted as hh:mm:ss, but this could be any other format.

In the example, we split the string on each colon, to get an array of substrings. The array contains the hours, minutes and seconds.

index.js
const str = '09:30:16'; // 👇️ ['09', '30', '16'] console.log(str.split(':'))

We then directly assigned the values to the hours, minutes and seconds variables using array destructuring.

To convert the hours to seconds, we had to multiple the value by 60 twice - once to convert to minutes and the second time to convert to seconds.

To convert the minutes to seconds, we multiplied by 60 once.

Because the results of the split operation are strings, we converted each value to a number and added them to one another.

If you only have a string that contains the hours and minutes (hh:mm), you can slightly tweak the function to convert to seconds.

index.js
const str = '09:30'; const [hours, minutes] = str.split(':'); function convertToSeconds(hours, minutes) { return Number(hours) * 60 * 60 + Number(minutes) * 60; } console.log(convertToSeconds(hours, minutes)); // 👉️ 34200

The string above is formatted as hh:mm, so we removed the third parameter of the function and converted the hours and minutes to seconds.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.