Number of Tuesdays This Month
Join the Discussion
var dd = new Date(y,m,0);
return (dd.getDate() -(dd.getDay() - w + 7) % 7 > 28) ? 5 : 4;
The weekdayMonth function takes three parameters. These are - the four digit year number, the number of the month (1 = january, 12 = december) and the day of the week you want to count the days for (0 = Sunday, 6 = Saturday). Simply pass in these three values and that function will then return an answer of 4 or 5 which is the number of days that will be on that day of the week in that month.
So how does it work? Well the first line creates a date object that contains the date for the last day of the month which is returned by dd.getDate(). dd.getDay retrieves the day of the week on which the last day of the month falls. The rest of the calculation determines the date of the last day of the month that falls on our selected day of the week. If that date is after the 28th then there are five of that day in the month, otherwise there are only four and it returns the appropriate one of those two numbers.
So if we call the function to ask for the number of Tuesdays there are in this month then the answer we get back is .