0

Code here:

const d = new Date(2020, 9, 31);
d.setMonth(8);
console.log(d);
// Result: Thursday October 1st (pardon can't type the whole thing, but you get what my problem is).

I expected September, pls help

  • 3
    Months are numbered from 0 (January); thus 9 is October. There are only 30 days in September, so your Date rolls over to October. That's how JavaScript Date instances work. – Pointy Jun 04 '20 at 18:39

1 Answers1

0

According to mdn: The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

So since your date has '31st' as day, after setting the month to September, it calculates '31' days hence you get the same month.

Sree.Bh
  • 1,751
  • 2
  • 19
  • 25