Find the nth Specific Weekday in a Month

January 13th, 2006

As part of a small feature that I developed, I had to figure out a way to find the 3rd Wednesday in a given month. While searching over the web I couldn’t find any C# example, so I’m posting here my suggestion for others who may need the same in the future and I would really appreciate any improvement ideas (please keep in mind that i had to support multiple regions, therefore you cannot assume that the first day of the week is Monday, it can by Sunday as well in other regions).

public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week)
{
// validate month value
if(month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(“Invalid month value.”);
}

// validate the nth value
if(nth < 0 || nth > 5)
{
throw new ArgumentOutOfRangeException(“Invalid nth value.”);
}

// start from the first day of the month
DateTime dt = new DateTime(year, month, 1);

// loop until we find our first match day of the week
while(dt.DayOfWeek != day_of_the_week)
{
dt = dt.AddDays(1);
}

if(dt.Month != month)
{
// we skip to the next month, we throw an exception
throw new ArgumentOutOfRangeException(“The given month has less than ” nth.ToString() ” ”
day_of_the_week.ToString() “s”);
}

// Complete the gap to the nth week
dt = dt.AddDays((nth – 1) * 7);

return dt;
}
tpg chubbymovies interracial cuckold house wiveschubby kirsten teen modelnude young teens tinyhairy nude women freeshare wife .uk amateurfat squirtingporn lezbian ebony movies freemassive breasts minkadad sex story mom

Comments are closed.