1

This is driving me crazy!

console.log(new Date(2020, 11, 4));

A simple date, 4th of November 2020.

Output:

Fri Dec 04 2020 00:00:00 GMT+0000 (Greenwich Mean Time)

WHAT!

So lets try an alternative:

const now = new Date()
console.log(now.getFullYear(), now.getMonth(), now.getDate());

Outputs:
Thu Oct 29 2020 10:12:56 GMT+0000 (Greenwich Mean Time)

Lets confirm some things now:

typeof now.getFullYear();
"number"

typeof now.getMonth();
"number"

typeof now.getDate();
"number"

typeof 2020
"number"

typeof 11
"number"

typeof 4
"number"

What is going on?

Adsy2010
  • 525
  • 6
  • 23

1 Answers1

3

Check out the Date constructor:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

So new Date(2020, 0, 1) is 01.01.2020, and your test case new Date(2020, 11, 4) is not Nov 4th, but Dec 4th.

konrad_pe
  • 1,189
  • 11
  • 26