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

Why Does JavaScript\'s `new Date()` Show October When Given Month 9?

Susan Sarandon
Release: 2024-11-25 08:56:15
Original
880 people have browsed it

Why Does JavaScript's `new Date()` Show October When Given Month 9?

Discrepancy in Date Creation with JavaScript

In the provided JavaScript code snippet, a Date object is created with the following parameters:

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

However, upon logging the created myDate, it displays the month as October instead of September. This discrepancy arises due to the difference in month notation in JavaScript.

In JavaScript, the month parameter in the Date constructor represents the zero-based index of months, ranging from 0 to 11. Therefore, September, which is the ninth month, is represented by the index 8. This explains why the code snippet creates a Date object with a month value of 9, resulting in the display of October.

The reference for the Date constructor confirms this behavior:

new Date(year, month [, day, hour, minute, second, millisecond]);
Copy after login

Under the month parameter, it explicitly states:

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

Therefore, in JavaScript, when creating a Date object, it is crucial to remember that month indices begin from 0, making it necessary to subtract 1 from the month number to obtain the intended result.

The above is the detailed content of Why Does JavaScript\'s `new Date()` Show October When Given Month 9?. 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