Reputation: 963
In short: Can someone please 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));
What I'm really interested in understanding is, why there is a "0" after month? I just can't seem to get my head round it, I've tried to omit it, and also replacing it with "day" but both with different outcome. This function only seems to work when the "0" is passed in the Object.
Also another tricky part when calling the function, passing "0" and "1" to represent January both return the same number of days where as passing "12" and "11" to represent December return different number of days (12 returns 31 (December) and 11 returns 30 (November)).
Upvotes: 3
Views: 142
Reputation: 687
The key is the JS Date object constructor. This function takes multiple parameters, but three are required: year, month, day. The day param is the day of the month, with the first day of the month being numbered as 1. The code above is really tricky. According to JS reference passing 0 for date, actually results in the last day of the PREVIOUS month. So this actually explains both the day question you have as well as the month question at the end.
See for more info: http://www.w3schools.com/jsref/jsref_setdate.asp
Passing 0 and 1 do not actually both represent January -- 1 represents january and 0 represents december of the previous year, which also has 31 days! (try running this function the year AFTER a year with a leap day, they wont have the same number of days).
Edit: Example To get a better grasp of what is actually happening, 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
}
Upvotes: 2
Reputation: 414086
JavaScript Date objects "fix" date settings that make no sense. Requesting a Date instance for day 0 in a month instead gives you a Date for the last day in the previous month.
Months are numbered from zero, but that function is written as if months were numbered from 1. You therefore get the same answer when you pass 0 or 1 as the month number because you're getting the number of days in the months December and January, and both of those months have 31 days.
Personally I would not have written that function that way; since it's necessary to keep in mind that months are numbered from zero in JavaScript, I'd have written the 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'd call it like this:
var janDays = daysInMonth(0, 2015);
Upvotes: 4