In java script given a month like "October"
how do I convert to a month to number format?
Output should be "10", for example.
i have variable called monthName it is giving value as "october",
now how can i convert monthName value as 10
In java script given a month like "October"
how do I convert to a month to number format?
Output should be "10", for example.
i have variable called monthName it is giving value as "october",
now how can i convert monthName value as 10
It's a bit of a hack, but:
var monthName = "October";
var monthNumber = new Date(monthName + " 1").getMonth() + 1;
console.log(monthNumber); // 10;
Perhaps it's overkill if this is the only work that you will be doing with dates but you could use the moment.js library:
moment("October", "MMM").format("M")
Output:
10
Obviously, you can use the name of a variable instead of the string literal "October".
You can just do this
function getMonthName() {
getMonthName.mnths = getMonthName.mnths || ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
return (getMonthName.mnths.indexOf(monthName.toLowerCase()) + 1);
}
console.log(getMonthName("October")); // 10
Just create an array of months, and add one to the index of the month you're trying to find.
This solution is 34% faster than using Date object. This solution DOES NOT allow for terms such as Oct
and doesn't care for locales, but that isn't asked for, anyway. If you need them, go with Date
object.
Also, this is among the good solutions as new Date("October 1").getMonth() + 1
will give you NaN
in IE10 & 11(The latest of the IEs) and even in the latest Mozilla Firefox.
This solution is cross-browser compatible, is more efficient, and certainly not a bad way of solving the problem. JS Perf