i need to convert Monthname to integer of that month (and want to avoid a big switch statement). any ideas?
Just create a date in that month, parse it, and use getMonth()
like this
function convertMonthNameToNumber(monthName) {
var myDate = new Date(monthName + " 1, 2000");
var monthDigit = myDate.getMonth();
return isNaN(monthDigit) ? 0 : (monthDigit + 1);
}
alert(convertMonthNameToNumber("August")); //returns 8
alert(convertMonthNameToNumber("Augustsss")); //returns 0 (or whatever you change the default too)
alert(convertMonthNameToNumber("Aug")); //returns 8 - Bonus!
alert(convertMonthNameToNumber("AuGust")); //returns 8 - Casing is irrelevant!
var monthtbl = { 'January': 1, 'February': 2, /* ... */, 'August', 8, /* ... */, 'December': 12 };
// ...
var monthNumber = monthtbl[monthName];
edit but do it the way @Chad suggests :-)
If you wanted to make it insensitive to alphabetic case, you'd create the object ("monthtbl") all lower-case and then use
var monthNumber = monthtbl[monthName.toLowerCase()];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With