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

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

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

+1


source to share


4 answers


You can add a dummy day and year to the month name and then use the Date constructor :



var month = (new Date("December 1, 1970").getMonth() + 1);

      

+4


source


Out of the box, this is not supported in native JS. As mentioned, there are language considerations and different timing conventions that you need to serve.



Do you have any mitigation assumptions that you can use?

+2


source


I recommend jQuery's datepicker utility functions .

+1


source


Try the following:

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);
}

      

+1


source







All Articles