JavaScript Date Object extracting number of days - function breakdown

In short: can someone explain to me what is going on with this function:

function daysInMonth(month, year){
            return new Date(year, month, 0).getDate();
}
alert(daysInMonth(1, 2013));

      

I'm really interested in understanding why there is a "0" after a month? I just can't think it over, I tried to skip it and also replace it with "day", but both with a different result. This function works only when "0" is passed in the object.

Another tricky part when calling a function passing "0" and "1" for the January view returns the same number of days when a different number of days is returned for the “12” and “11” for the December view (12 returns 31 (December) and 11 returns 30 (November)).

+3


source to share


2 answers


JavaScript "Fix" date objects that don't make sense. Query for an instance of the date for day 0 in the month instead gives you the date of the last day in the previous month.

The months are numbered from zero, but this function is written as if the months were numbered from 1. So you get the same answer when you pass 0 or 1 as the month number, because you get the number of days in the months December and January and both of these months have 31 days.

Personally, I would not write this function this way; Since you need to keep in mind that months are numbered from zero in JavaScript, I would write a function like this:



function daysInMonth(month, year){
   return new Date(year, month + 1, 0).getDate();
}

      

Then, to get the number of days in January, you would call it like this:

var janDays = daysInMonth(0, 2015);

      

+4


source


The key is the constructor of the JS Date object. This function takes several parameters, but three are required: year, month, day. The day parameter is the day of the month whose first day of the month is numbered 1. The code above is really complicated. According to the JS link, passing 0 for a date actually results in the last day of the PREVIOUS month. So it actually explains both the day's question you have and the question of the month at the end.

See more information: http://www.w3schools.com/jsref/jsref_setdate.asp

Passing 0 and 1 doesn't really represent January - 1 represents January and 0 represents December of the previous year, which also has 31 days! (try running this function a year AFTER one year with a leap day, they won't have the same number of days).



Edit: Example To better understand what's really going on, try running this function:

function check() {
    console.log(new Date(2015, 0, 0).toISOString());  // 2014-12-31T08:00:00.000Z
    console.log(new Date(2015, 1, 0).toISOString());  // 2015-01-31T08:00:00.000Z
    console.log(new Date(2015, 11, 0).toISOString());  // 2015-11-30T08:00:00.000Z
    console.log(new Date(2015, 12, 0).toISOString());  // 2015-12-31T08:00:00.000Z
}

      

+2


source







All Articles