tags:

views:

142

answers:

4

Is there a built in Javascript function to turn the text string of a month into the numerical equivalent?

Ex. I have the name of the month "December" and I want a function to return "12".

+1  A: 

I recommend jQuery's datepicker utility functions.

kgiannakakis
It seems silly to install a Javascript library just for this one function. Is it not built into Javascript?
Bloudermilk
I can't say for sure, but it seems unlikely, since locale must be taken into consideration. This is open source, read the code to see how they do it.
kgiannakakis
+2  A: 

Out of the box, this is not something supported in native JS. As mentioned, there are locale considerations, and different date conventions which you need to cater to.

Do you have any easing assumptions you can use?

Yuval A
+1  A: 

Try this:

function getMonthNumber(monthName) { 

    // Turn the month name into a parseable date string.
    var dateString = "1 " + monthName;

    // Parse the date into a numeric value (equivalent to Date.valueOf())
    var dateValue = Date.parse(dateString);

    // Construct a new JS date object based on the parsed value.
    var actualDate = new Date(dateValue);

    // Return the month. getMonth() returns 0..11, so we need to add 1
    return(actualDate.getMonth() + 1);
}
Dylan Beattie
+4  A: 

You can append some dummy day and year to the month name and then use the Date constructor:

var month = (new Date("December 1, 1970").getMonth() + 1);
Darin Dimitrov
Simple and effective, thanks so much.
Bloudermilk
I'm not sure this will work with different locale. But if the developer can take an easing assumption on this, this is a good solution.
Yuval A