Search code examples
javascriptdate

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


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.


Solution

  • 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