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".
From stackoverflow
-
I recommend jQuery's datepicker utility functions.
Bloudermilk : It seems silly to install a Javascript library just for this one function. Is it not built into Javascript?kgiannakakis : 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. -
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);
Bloudermilk : Simple and effective, thanks so much.Yuval A : 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.
0 comments:
Post a Comment