Home > Web Front-end > JS Tutorial > Why Does JavaScript\'s `Date` Object Use a Zero-Based Month Index?

Why Does JavaScript\'s `Date` Object Use a Zero-Based Month Index?

Barbara Streisand
Release: 2024-11-29 15:06:17
Original
696 people have browsed it

Why Does JavaScript's `Date` Object Use a Zero-Based Month Index?

Javascript Date Month Discrepancy

In Javascript, the Date object constructor takes a month parameter that represents the month of the year, starting with 0 for January to 11 for December. This is contrary to the common convention of starting months with 1 for January and ending them with 12 for December.

Example

Consider the following code:

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

Instead of printing a date in October, as one might expect, it prints the following:

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

This is because Javascript interprets the 9th month parameter as October, since it follows the zero-based indexing for months.

Resolution

To specify a date in October using Javascript, you should use the month index 9, not 10. For example:

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

The above is the detailed content of Why Does JavaScript\'s `Date` Object Use a Zero-Based Month Index?. 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