admin管理员组文章数量:1278948
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.
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.
Share Improve this question edited Aug 30, 2018 at 14:38 benvc 15.1k4 gold badges38 silver badges57 bronze badges asked Apr 3, 2017 at 10:49 Devanshi SukhijaDevanshi Sukhija 1671 silver badge10 bronze badges 5- 1 have you done any research? – Sagar V Commented Apr 3, 2017 at 10:50
- You can refer to stackoverflow./a/42851567/3783478 – Rajesh Commented Apr 3, 2017 at 10:52
- 3 Actually, it gives the number of days in the month prior to a particular month. – David Schwartz Commented Apr 3, 2017 at 10:55
- @DavidSchwartz that is correct, however, considering how javascript Date enumerates months, it seems like it gives the length of specified month. – Matteo Tassinari Commented Apr 3, 2017 at 10:57
-
@MatteoTassinari Only if you've never used the
Date
constructor for anything else. ;) – David Schwartz Commented Apr 3, 2017 at 10:58
2 Answers
Reset to default 10When 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
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
本文标签:
版权声明:本文标题:Why does JavaScript: new Date(year, month, 0).getDate() return the number of days in the month? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741231520a2362196.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论