Borislav Hadzhiev
Thu Jan 20 2022·2 min read
Photo by Joshua Reddekopp
To convert hh:mm:ss
to seconds:
60
twice.60
.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
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.
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.
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.
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.