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

Why Does JavaScript\'s getMonth() Return the Previous Month for Dates in Some Months?

Susan Sarandon
Release: 2024-10-19 13:18:29
Original
117 people have browsed it

Why Does JavaScript's getMonth() Return the Previous Month for Dates in Some Months?

JavaScript's getMonth() Returns Previous Month: A Datepicker Anomaly

Encountering discrepancies in date extraction from a datepicker can be puzzling. In particular, the getMonth() method may yield the previous month instead of the expected one. To illustrate this issue:

<code class="javascript">var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
console.log(d1.getMonth()); // Output: 6 (June)</code>
Copy after login

Unveiling the Reason

The root cause lies in JavaScript's getMonth() method, which considers January as month 0 and December as month 11. As a result, if you obtain a Date object for a date in July, the getMonth() method will return 6, indicating June.

Rectifying the Anomaly

To resolve this issue and obtain the actual month number corresponding to the given date, simply increment the result of getMonth() by 1.

<code class="javascript">console.log(d1.getMonth() + 1); // Output: 7 (July)</code>
Copy after login

By adding 1 to the month number obtained from getMonth(), you can accurately capture the intended month.

The above is the detailed content of Why Does JavaScript\'s getMonth() Return the Previous Month for Dates in Some Months?. 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
Latest Articles by Author
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!