Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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