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.
Solution 1:
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
Solution 2:
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
}
Post a Comment for "Convert Time String To Seconds In Javascript/jquery"