Parse a natural duration into seconds in JavaScript
I wrote this for a little Chrome extension I maintain and thought it might be useful to someone else. It parses a natural language duration like "1h30m" or "37 days, 1 hr, 3 mins and 7s" into a straight number of seconds:
// Try to be as sensible as possible about parsing durations
function parseDuration(duration) {
// .75
if (match = /^\.\d+$/.exec(duration)) {
return parseFloat("0" + match[0]) * 3600;
// 4 or 11.75
} else if (match = /^\d+(?:\.\d+)?$/.exec(duration)) {
return parseFloat(match[0]) * 3600;
// 01:34
} else if (match = /^(\d+):(\d+)$/.exec(duration)) {
return (parseInt(match[1]) || 0) * 3600 + (parseInt(match[2]) || 0) * 60;
// 1h30m or 7 hrs 1 min and 43 seconds
} else if (match = /(?:(\d+)\s*d(?:ay?)?s?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*h(?:(?:ou)?rs?)?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*m(?:in(?:utes?))?)?(?:(?:\s+and|,)?\s+)?(?:(\d)\s*s(?:ec(?:ond)?s?)?)?/.exec(duration)) {
return (parseInt(match[1]) || 0) * 86400 + (parseInt(match[2]) || 0) * 3600 + (parseInt(match[3]) || 0) * 60 + (parseInt(match[4]) || 0);
// Unknown!
} else {
return null;
}
};