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

Why Does JavaScript\'s Date Constructor Return October When I Provide 9 for the Month?

Patricia Arquette
Release: 2024-10-30 17:22:03
Original
812 people have browsed it

Why Does JavaScript's Date Constructor Return October When I Provide 9 for the Month?

Navigating Month Discrepancies in JavaScript's Date Constructor

When working with dates in JavaScript, it's crucial to understand the peculiarity of how months are indexed. A recent query on Mozilla Firefox Firebug raised concerns:

var myDate = new Date(2012, 9, 23, 0, 0, 0, 0);
console.log(myDate);
Copy after login

Output:

Date {Tue Oct 23 2012 00:00:00 GMT-0400 (Eastern Daylight Time)}
Copy after login

Delving into the discrepancy, the user observed an unexpected result: JavaScript returned a date in October instead of September, as intended.

Unveiling the Truth: Zero-Based Indexing

The key lies in the zero-based indexing used by JavaScript's Date constructor for months. In this indexing scheme, months start with 0 for January, and 11 represents December. Therefore, the month index passed in the constructor (9) actually corresponds to October, not September.

Clarifying with References:

The Mozilla Developer Network (MDN) provides explicit guidance:

month: Integer value representing the month, beginning with 0 for January to 11 for December.
Copy after login

Additionally, the ECMAScript language specification offers a technical insight:

7. Let mn be ?(ℝ(m) modulo 12).
Copy after login

This line elucidates that the month input undergoes a modulo operation with 12, effectively wrapping the month index within the range of 0 to 11.

Therefore, when constructing a date in JavaScript, it's essential to remember that months are zero-indexed to avoid any confusion or unexpected outcomes.

The above is the detailed content of Why Does JavaScript\'s Date Constructor Return October When I Provide 9 for the Month?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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!