javascript is creating date wrong month

Javascript

Javascript Problem Overview


using Mozilla Firefox Firebug:

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

Date {Tue Oct 23 2012 00:00:00 GMT-0400 (Eastern Daylight Time)}

Why does javascript create the date with the wrong month?

Javascript Solutions


Solution 1 - Javascript

No, javascript's Date months start with 0, so 9 is a 10th month and it is October

Reference:

> new Date(year, month [, day, hour, minute, second, millisecond]); > > [...] > > month > Integer value representing the month, beginning with 0 for January to 11 for December.

Solution 2 - Javascript

In the javascript world months begin with zero! kind of weird to me. Anyhow, 9 is NOT September, but rather 9 is October.

Solution 3 - Javascript

Use a string as a parameter to avoid that weird behavior of Date constructor.

Example:

const myDate = new Date('2021-08-13'); // Result: Fri Aug 13 2021 02:00:00 GMT+0200...

Solution 4 - Javascript

In javascript Date object mounts are starting from ( 0 to 11 ) its funny :)

just always write

new Date(yea,month - 1,seconds ,millisecond)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe KahlView Question on Stackoverflow
Solution 1 - JavascriptzerkmsView Answer on Stackoverflow
Solution 2 - JavascriptJoe KahlView Answer on Stackoverflow
Solution 3 - JavascriptCrepkeyView Answer on Stackoverflow
Solution 4 - JavascriptMenooa EskandarianView Answer on Stackoverflow