Created
October 28, 2011 02:20
-
-
Save JayDouglass/1321475 to your computer and use it in GitHub Desktop.
FindNthOccurenceOfWeekDayForMonth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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