Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the month number from a given month name

Tags:

javascript

I'm trying to find the corresponding month number from a given month name. What the easiest way of achieving this is?

like image 649
user1746560 Avatar asked Nov 01 '12 13:11

user1746560


3 Answers

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.

like image 138
Henrik Aasted Sørensen Avatar answered Nov 19 '22 07:11

Henrik Aasted Sørensen


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());
like image 5
CompanyDroneFromSector7G Avatar answered Nov 19 '22 07:11

CompanyDroneFromSector7G


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.

like image 3
RobG Avatar answered Nov 19 '22 06:11

RobG