JavaScript Is Creating Date Wrong Month

new Date() sets wrong month

Month dates start at 0 in javascript, so 0 would be January and 11 would be December in your example.

Why does new Date(2018,12, 25) give the wrong month and year?

See MDN:

Note: The argument monthIndex is 0-based. This means that January = 0 and December = 11.

So month 12 is the 13th month of the year, which rolls over and becomes January of the next year.

Creating date with numbers (new Date(2012, 03, ...) gives wrong month (+1)

Programmers start counting from 0. So months are represented by 0(Jan)-11(Dec).

The reason days don't follow this rule is to not confuse authors with 30/31 month differences.

From MDN:

month

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

JS date giving wrong month

I ended up finding out that its because of timezones. I should of guess that, but if anyone else is in need of a fix you can simple add the time to the date to bring it to the actual date.

const date = new Date('2021-05-01 00:00:00');

Formatting date method returns wrong month

JS month range is from 0-11. So you have to add 1 to month.

const formatingDate = (dates) => {

const d = new Date(dates);

return `${(d.getMonth() + 1)

.toString()

.padStart(2, '0')}/${d

.getDate()

.toString()

.padStart(2, '0')}/${d.getFullYear()}`;

};

console.log(formatingDate('2019-07-24'))

JS Date creating incorrect dates/JS Date confusion

I believe the issue you are facing is the result of malformed date strings (or at least it very well might be). getMonth and day are both numbers which means that when they are less than 10, they will be a single character string. 2022-1-1 is not a valid date for JS to parse. padStart can help format it correctly.

Try:

const date = new Date(`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(day + 1).padStart(2, "0")}`);


Related Topics



Leave a reply



Submit