Home > Web Front-end > JS Tutorial > body text

Why Does getMonth() Return the Previous Month in JavaScript?

DDD
Release: 2024-10-19 13:15:29
Original
689 people have browsed it

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!