Getting the month number on behalf of the month

I am trying to find the number of the corresponding month on behalf of the month. What is the easiest way to achieve this?

+6
source share
6 answers

In this case, there is no need for jQuery.

JavaScript in these lines can help:

var monthNumber = ["january", "february", "march"].indexOf(monthname.toLowerCase()) + 1; 

Expand the array with all the months to make it fully functional.

+13
source

A simplified method for getting values ​​from 0 (January) to 11 (December):

 var monthString = 'December'; var dat = new Date('1 ' + monthString + ' 1999'); alert(dat.getMonth()); 
+4
source

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 take various forms of the month name, such as Jan, jan, JAN, January, JANUARY, etc.

Oh, the above assumes you need a month number, as for entering a javascript date constructor. To get the month number of the calendar, simply increase the values ​​by 1.

+3
source

You do not need jQuery because this can be easily resolved by javascript.

Use a pair of key values, like the following

 var months = {jan:1, feb:2, mar:3, apr:4, may:5, jun:6}; 

You can easily get the month number by specifying the name of the month, for example, the following

 months.jan // will return 1 to the caller 

or

 alert(months.feb); //will shows 2 in message box; 
+3
source

Depending on where this information comes from, you may be interested in using the DateJS library:

It does not use jquery, but it is good for parsing. If you look in the Download section, it also contains over 150 internationalized libraries if you need to handle foreign language input.

+1
source

The way I do this is as follows:

Create an array with all months;

 var data=new Array("January","February","March","April","May","June","July","August","September","October","November","December") //Lets say you get this back from your get month function. This should return january, because that is the first month.. var numberOfMonth = 1; //An array starts with the index 0, so you could do minus 1 to get the correct one alert data[numberOfMonth - 1]); 
+1
source

All Articles