Reputation: 167
I know that this little javascript code,var whatever = new Date(year, month, 0).getDate()
, returns the number of days in a particular month of a particular year. But what I don’t seem to understand is the logic behind it.
What exactly is that zero doing there after we mention the year and the month? Please Explain.
Upvotes: 7
Views: 6270
Reputation: 11
If any parameter overflows its defined bounds, it "carries over". For example, if a monthIndex greater than 11 is passed in, those months will cause the year to increment; if a minutes greater than 59 is passed in, hours will increment accordingly, etc. Therefore, new Date(1990, 12, 1) will return January 1st, 1991; new Date(2020, 5, 19, 25, 65) will return 2:05 A.M. June 20th, 2020.
Similarly, if any parameter underflows, it "borrows" from the higher positions. For example, new Date(2020, 5, 0) will return May 31st, 2020.
Upvotes: 1
Reputation: 182819
When you give a parameter out of range, the next larger time increment is adjusted to make the time valid. So:
> new Date(2016,2,1)
2016-03-01T08:00:00.000Z
So if we specify (2016,2,1), we get 3/1. So if we specify (2016,2,0), we'll get a day before that, adjusting the month as necessary to get something valid, that is, the last day of the previous month.
> new Date(2016,2,0)
2016-02-29T08:00:00.000Z
Upvotes: 10