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:
- 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!