Home > Software design >  Why does this return the number of days in a month?
Why does this return the number of days in a month?

Time:09-05

I googled 'Javascript find number of days in month" and found this blog entry. I read it 5 times thinking "This won't work". But it does.

new Date(2022,8,0).getDate()

Can someone explain why/how this returns 31 instead of an error?

CodePudding user response:

Basically, the "why" is "the spec told us to". The ECMAScript specification says that the day portion of the values passed to the constructor should be made safe by taking the modulo of the value and 12. It is then passed through some other calculations such that values "wrap" to the preceding or succeeding month.

Passing string values drives these algorithms a little crazy, as answers to Is the Javascript date object always one day off? demonstrate.

In any case, taking care to validate arguments to the Date constructor beforehand before blindly taking what is returned is always a good idea.

  • Related