Skip to content

Instantly share code, notes, and snippets.

@axemclion
Created October 5, 2009 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axemclion/202099 to your computer and use it in GitHub Desktop.
Save axemclion/202099 to your computer and use it in GitHub Desktop.
Interval Parser - from "English" to "Seconds"
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