Skip to content

Instantly share code, notes, and snippets.

@boucher
Created July 8, 2011 00:32
Show Gist options
  • Save boucher/1070862 to your computer and use it in GitHub Desktop.
Save boucher/1070862 to your computer and use it in GitHub Desktop.
Parse months and years from a string
function parseExpirationDate(string)
{
var components = string.split(/\b/);
var index = components.length;
var month, year;
// first we parse the words (so that month names can appear in any order)
while (index--) {
if (isNaN(parseInt(components[index]))) {
var candidateMonth = (new Date(components[index]+" 1, 2000")).getMonth();
if (!isNaN(candidateMonth)) {
month = candidateMonth + 1;
}
components.splice(index, 1);
}
}
// then we parse numbers
index = components.length;
while (index--) {
var string = components[index];
var number = parseInt(string);
if (string.length > 2 || number > 12) {
year = number;
} else if (year === undefined) {
year = number;
} else {
month = number;
}
}
if (year < 100)
year += Math.floor(new Date().getFullYear()/100)*100;
return {
month: month,
year: year,
success: !isNaN(new Date(["01", month || "_", year || "_"].join("/")).getTime())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment