Home > Web Front-end > JS Tutorial > Why does `new Date(2023, 9)` return October in JavaScript?

Why does `new Date(2023, 9)` return October in JavaScript?

Susan Sarandon
Release: 2024-10-29 09:56:02
Original
235 people have browsed it

 Why does `new Date(2023, 9)` return October in JavaScript?

Decoding JavaScript's Date Month Mystery

In JavaScript, the enigma of a mismatched month from the Date constructor stirs curiosity. Perplexingly, a date constructed with a month value of 9 returns October instead of the intended September.

Delving into the inner workings of JavaScript, we encounter the underlying logic behind this discrepancy. Unlike common conventions, JavaScript's Date object defines months starting from 0. Therefore, the provided value of 9 is interpreted as the tenth month, which corresponds to October.

This subtle design decision is corroborated by the Mozilla Developer Network (MDN):

month

Integer value representing the month, beginning with 0 for January to 11 for December.

Further confirmation comes from the language specification itself:

  1. Let mn be ?(ℝ(m) modulo 12).

This mathematical formula effectively wraps the month value around a modulus of 12, ensuring that it always falls within the range of 0 to 11.

Thus, the month value provided in the code is correctly converted to the corresponding October based on JavaScript's month definition.

The above is the detailed content of Why does `new Date(2023, 9)` return October in JavaScript?. 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