1

what is the problem and how to fix this ?

> new Date(2022,5,31)
< Fri Jul 01 2022 00:00:00 GMT+0430 (Iran Daylight Time)
> new Date("2022-5-31")
< Tue May 31 2022 00:00:00 GMT+0430 (Iran Daylight Time)

creating Date(2022,5,31) object

  • @SumitSharma thanks for answering ; but i tried new new Date("2022-05-31") and the result is < Tue May 31 2022 04:30:00 GMT+0430 (Iran Daylight Time) {} – Menooa Eskandarian May 31 '22 at 09:29

2 Answers2

3

Month is 0 indexed, i.e. 0 represents January. When you pass in a string with explicit date formatting like "2022-5-31" the month is not 0 indexed.

> new Date(2022,5,31)
                ^
              June
                   ^ 
                   31 -> 01 of the next month (Jul)
< Fri Jul 01 2022 00:00:00 GMT+0430 (Iran Daylight Time)

> new Date("2022-5-31")
                 ^
                May
                    ^
                   31 valid day
< Tue May 31 2022 00:00:00 GMT+0430 (Iran Daylight Time)

This becomes explicit when you try putting days of 35, for example:

> console.log(new Date(2022, 05, 35));
< Tue Jul 05 2022 00:00:00 GMT+0100 (British Summer Time)
ChrisOram
  • 1,254
  • 1
  • 5
  • 17
1

In the first example, January is 0 while in the second example, January is 1.

June only has 30 days so the extra 31st rolls over into July.

Richie Bendall
  • 7,738
  • 4
  • 38
  • 58