Created
April 20, 2011 06:50
-
-
Save sj26/930528 to your computer and use it in GitHub Desktop.
Parses a natural duration string into seconds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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