Why Does JavaScript's getMonth() Return the Previous Month?
When using a datepicker that provides a date in the format "Sun Jul 7 00:00:00 EDT 2013," you might notice that the getMonth() method returns the previous month. For instance, the code snippet below:
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013"); d1.getMonth(); //gives 6 instead of 7
The Reason:
The reason for this discrepancy lies in the fact that JavaScript's getMonth() method assigns months a zero-based index. Therefore, January is assigned the value of 0, February is assigned 1, and so on. When calling getMonth() on a date representing July, it actually returns the value for June (6).
Solution:
To obtain the correct month, you can use the following adjusted code:
d1.getMonth() + 1; //returns the correct month, which is 7 for July
By adding 1 to the result of getMonth(), you offset the zero-based index and obtain the month as per calendar convention.
The above is the detailed content of Why Does JavaScript\'s getMonth() Yield the Previous Month\'s Value?. For more information, please follow other related articles on the PHP Chinese website!