Convert HH:MM:SS string to seconds only in javascript
Try this:
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);
This function handels "HH:MM:SS" as well as "MM:SS" or "SS".
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0, m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
This can be done quite resiliently with the following:
'01:02:03'.split(':').reduce((acc,time) => (60 * acc) + +time);
This is because each unit of time within the hours, minutes and seconds is a multiple of 60 greater than the smaller unit. Time is split into hour minutes and seconds components, then reduced to seconds by using the accumulated value of the higher units multiplied by 60 as it goes through each unit.
The +time
is used to cast the time to a number.
It basically ends up doing: (60 * ((60 * HHHH) + MM)) + SS
If only seconds is passed then the result would be a string, so to fix that we could cast the entire result to an int:
+('03'.split(':').reduce((acc,time) => (60 * acc) + +time));