Why does JavaScript: new Date(year, month, 0).getDate() return the number of days in the month?
Asked Answered
C

2

7

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.

Clangor answered 3/4, 2017 at 10:49 Comment(5)
have you done any research?Vacla
You can refer to https://mcmap.net/q/1480269/-javascript-validate-date-and-return-last-available-date-of-calendarRecurved
Actually, it gives the number of days in the month prior to a particular month.Ragsdale
@DavidSchwartz that is correct, however, considering how javascript Date enumerates months, it seems like it gives the length of specified month.Relume
@MatteoTassinari Only if you've never used the Date constructor for anything else. ;)Ragsdale
R
10

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
Ragsdale answered 3/4, 2017 at 10:57 Comment(0)
P
1

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.

MDN

Ploy answered 25/12, 2023 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.