Convert HH:MM:SS string to seconds only in javascript

Solution 1:

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);

Solution 2:

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;
}

Solution 3:

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));

Solution 4:

Since the getTime function of the Date object gets the milliseconds since 1970/01/01, we can do this:

var time = '12:23:00';
var seconds = new Date('1970-01-01T' + time + 'Z').getTime() / 1000;

Solution 5:

Convert hh:mm:ss string to seconds in one line. Also allowed h:m:s format and mm:ss, m:s etc

'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)