Home > Web Front-end > JS Tutorial > Why Does JavaScript\'s getMonth() Yield the Previous Month\'s Value?

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

DDD
Release: 2024-10-19 13:17:01
Original
1101 people have browsed it

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
Copy after login

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
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template