Barry Hamilton
Barry Hamilton

Reputation: 973

convert time string to seconds in javascript/jquery

I have a timeuntil string displayed as 12d 00:57:30 ie. dd'd' hh:mm:ss

How would I convert that into number of seconds in javascript or jquery.

Upvotes: 0

Views: 2524

Answers (2)

Pablo Matias Gomez
Pablo Matias Gomez

Reputation: 6823

I know this will not sound good for some, but if you don't want to use a plugin like moment.js. You could parse it like this (only for format dd'd' hh:mm:ss):

var days = parseInt(time.split('d ')[0]);
var hours = parseInt(time.split('d ')[1].split(":")[0]);
var mins = parseInt(time.split('d ')[1].split(":")[1]);
var secs = parseInt(time.split('d ')[1].split(":")[2]);

hours += days * 24;
mins += hours * 60;
secs += mins * 60;

secs will be the total

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

For things like this, I love moment.js. It has something called "durations" that would be perfect for this situation.

First, you'd need to parse your string into its pieces. Since you know the format, we can use a regex.

var time = '12d 00:57:30';
var timeParts = time.match(/(\d+)d (\d{2}):(\d{2}):(\d{2})/);

if(timeParts !== null){
    var timeUntil = moment.duration({
        days: timeParts[1],
        hours: timeParts[2],
        minutes: timeParts[3],
        seconds: timeParts[4]
    });
    var timeSeconds = timeUntil.as('seconds');

    console.log(timeSeconds);  // 1040250
}

Upvotes: 1

Related Questions