Skip to content

Instantly share code, notes, and snippets.

@JayDouglass
Created October 28, 2011 02:20
Show Gist options
  • Save JayDouglass/1321475 to your computer and use it in GitHub Desktop.
Save JayDouglass/1321475 to your computer and use it in GitHub Desktop.
FindNthOccurenceOfWeekDayForMonth
public DateTime FindNthOccurenceOfWeekDayForMonth(int month, int year, DayOfWeek weekDay, int occurence)
{
if(occurence < 1)
{
throw new ArgumentOutOfRangeException("occurence must be greater than 0");
}
// iterate over days, beginning with the first day of the given month and year
// loop until occurence = 0
// when loop exits current will be set to the nth occurence of weekDay
var current = new DateTime(year, month, 1);
while(true)
{
if(current.DayOfWeek == weekDay) occurence--;
if(occurence == 0) break;
current = current.AddDays(1);
}
if(current.Month != month)
{
throw new ArgumentOutOfRangeException("occurence for week day falls outside of given month");
}
return current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment