0

I try to use the date object from NodeJS v14.15.1. And when I instantiate the object with the year, month and day parameter. When I try to use the getDay() and getYear() method, I don't have the right number.

I really don't know what going on and why this method don't return what's I expected.

const date = new Date(2021, 4, 1) // I create a date object for 2021/04/01
console.log(date.getDay()) // This return 6 instead of 1
console.log(date.getYear()) // This return 121 instead if 2021
mplungjan
  • 169,008
  • 28
  • 173
  • 236
MrSolarius
  • 599
  • 11
  • 28
  • 1
    [RTM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#syntax) `const date = new Date(2021, 3, 1); console.log(date.getDay()); console.log(date.getfullYear())` – mplungjan Jul 26 '21 at 14:00

1 Answers1

2

There's some unfortunate historical naming of methods here. Check out MDN's documentation for Date.

  • getDay returns the day of the week (Sunday = 0, Monday = 1, etc.). You probably want to use getDate instead.

  • Similarly, getYear returns the year minus 1900. You probably want to use getFullYear instead.

  • Although you didn't mention it, note that getMonth is zero-based: 0 = January, 1 = February, etc. The same is true for new Date. So new Date(2021, 4, 1) corresponds to the ISO date 2021-05-01.

edemaine
  • 2,699
  • 11
  • 20