Skip to content

Instantly share code, notes, and snippets.

@sj26
Created April 20, 2011 06:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sj26/930528 to your computer and use it in GitHub Desktop.
Save sj26/930528 to your computer and use it in GitHub Desktop.
Parses a natural duration string into 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;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment