Home >Web Front-end >JS Tutorial >Why Does My JavaScript `Date` Object Show the Wrong Month?
Understanding the JavaScript Date Creation Discrepancy
When working with JavaScript's Date object, it's crucial to be aware of a slight difference in the way months are represented compared to most other programming languages.
Consider the following JavaScript code:
var myDate = new Date(2012, 9, 23, 0, 0, 0, 0); console.log(myDate);
In this code, we attempt to create a Date object representing October 23rd, 2012. However, when we log the resulting myDate object, we notice an unexpected result:
Date {Tue Oct 23 2012 00:00:00 GMT-0400 (Eastern Daylight Time)}
Instead of October, the date is reported as September. Why does JavaScript create the date with the wrong month?
The answer lies in the way JavaScript represents months in the Date object. Unlike many other languages, JavaScript starts counting months from 0, where 0 represents January and 11 represents December.
Therefore, in the above code:
As a result, JavaScript interprets the given parameters as September 23rd, 2012, which is why the logged date shows October 23rd, since September only has 30 days.
Reference:
The above is the detailed content of Why Does My JavaScript `Date` Object Show the Wrong Month?. For more information, please follow other related articles on the PHP Chinese website!