Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there anything in javascript that can convert "August" to 8?

i need to convert Monthname to integer of that month (and want to avoid a big switch statement). any ideas?

like image 235
leora Avatar asked Aug 25 '10 18:08

leora


2 Answers

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!
like image 128
CaffGeek Avatar answered Sep 18 '22 21:09

CaffGeek


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()];
like image 22
Pointy Avatar answered Sep 19 '22 21:09

Pointy