Home >Web Front-end >JS Tutorial >Why Does getMonth() Return the Previous Month in JavaScript?
getMonth Returns Previous Month in JavaScript: Understanding Month Numbering
In JavaScript, the getMonth method returns the month index of a given date. However, there can be a discrepancy between the displayed month and the value returned by getMonth.
When faced with this issue, where getMonth returns the previous month, it's essential to remember that JavaScript's month numbering starts from 0, meaning January is assigned the value 0, February is 1, and so on. This means that when a month is displayed as July (the seventh month), getMonth will return 6, representing the index of June.
To correct this discrepancy, you can add 1 to the result of getMonth. For example, using the code provided:
<code class="javascript">var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013"); console.log(d1.getMonth() + 1); // Output: 7</code>
By incrementing the result by 1, we obtain the actual month number, which is 7 for July. This allows you to manipulate dates and retrieve the correct month information in JavaScript.
The above is the detailed content of Why Does getMonth() Return the Previous Month in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!