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".
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".
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?
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);
}
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);