Days in a month function

Hello campers.

I am doing a calendar for practicing my js, and I was looking for a way to track the numbers of days that a specific month have, and I end up with this function.

function daysInMonth (year, month) {

  return new Date (year, month+1, 0).getDate();


It works pretty well, the problem is, I am struggling to understand how this work.

Thanks for helping me.

Ps: I was unable to format this block, if you cam helo me with this as well.

Calling “Date(2017,3,3)” gives you “Apr 03 2017”, not “March 3 2017”, which is what you’d expect.

The month parameter (2nd one) is zero based when used in the Date() function. It’s just as if you were specifying the member of an array, so 1 would be February, 11 is December, etc. and that is why it’s been modified in this call to Date() in this code, so that the month you get is the one you expected.

Mixing zero-based and one-based values is often a source of bugs and confusion.

As to formatting the code block, looks like you didi it. Just write the code, highlight it then click on the </> button in the toolbar to format a multi-line block, such as:


Thanks for the explanation man, the real doubt was because the 0. But I did sone tests and find out the why I was seeking.