Skip to content

Instantly share code, notes, and snippets.

@mansona
Forked from sj26/parseDuration.js
Created August 22, 2011 13:50
Show Gist options
  • Save mansona/1162408 to your computer and use it in GitHub Desktop.
Save mansona/1162408 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