"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does JavaScript's getMonth() return the value of last month?

Why does JavaScript's getMonth() return the value of last month?

Posted on 2025-04-15
Browse:940

Why Does JavaScript\'s getMonth() Yield the Previous Month\'s Value?

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.

Release Statement This article is reproduced on: 1729314917 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3