Created
October 5, 2009 12:56
-
-
Save axemclion/202099 to your computer and use it in GitHub Desktop.
Interval Parser - from "English" to "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
function parseInterval(interval){ | |
var u = {}; | |
u["minute"] = 1; | |
u["hour"] = 60 * u["minute"]; | |
u["day"] = 24 * u["hour"]; | |
u["week"] = 7 * u["day"]; | |
u["month"] = 30 * u["day"]; | |
u["quarter"] = 3 * u["month"]; | |
u["year"] = 365 * u["day"]; | |
var numbers = interval.match(/[0-9]+/g); | |
var words = interval.split(/[0-9]+/g); | |
var result = 0; | |
for (var i = 1; i < words.length; i++) { | |
for (unit in u) { | |
if (words[i].indexOf(unit) !== -1) { | |
var num = parseInt(numbers[i - 1], 10) * u[unit]; | |
if (!isNaN(num)) { | |
result += num; | |
} | |
} | |
} | |
} | |
if (result == 0) { | |
result = parseInt(interval, 10); | |
} | |
return isNaN(result) ? 0 : result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment