I'm trying to find the corresponding month number from a given month name. What the easiest way of achieving this is?
There is not really a need for jQuery in this case.
JavaScript along these lines might help:
var monthNumber = ["january", "february", "march"].indexOf(monthname.toLowerCase()) + 1;
Expand the array with all months to make it fully functional.
Simpler method to give a value from 0 (January) to 11 (December):
var monthString = 'December';
var dat = new Date('1 ' + monthString + ' 1999');
alert(dat.getMonth());
An alternative to Array.prototype.indexOf
is an object:
var months = {jan: 0, feb:1, mar:2 ...};
var monthName = 'January';
var monthNum = months[monthName.substring(0,3).toLowerCase()];
The advantage is that you can accept various forms of the month name such as Jan, jan, JAN, January, JANUARY, etc.
Oh, the above assumes you want month number as for a javascript Date constructor input. To get calendar month number, just increase the values by 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With