1. Computing

Number of Tuesdays This Month

Join the Discussion

Questions? Comments?

One rather interesting question that someone asked about coding in javaScript relates to determining the number of times that a given day of the week occurs in a specific month. We know that if we want to know how many Tuesdays that there are this month that the answer will be either four or five depending on what day of the week that the month starts on and how many days there are in the month. Exactly how you would convert that into something that JavaScript can understand is something that you don't have to worry about any more because I have have written the following function to do it for you. You are not even limited to this month specifically or to Tuesdays as this function will work with any month and any day of the week.

function weekdayMonth(y,m,w) {
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 .

Related Video
Create Bullet, Number, and Definition Lists in HTML

©2014 About.com. All rights reserved.