Get a List of Dates for the Nth Desired Day of Week in a Month for a Range of Dates






4.50/5 (4 votes)
This is an alternative for "Get a list of Dates for the Nth Desired Day of Week in a Month for a range of dates"
Introduction
The solution below is based on this tip by John Simmons and my alternative suggestions in its comments section.
The Code
public static List<DateTime> GetDatesByOrdinalDayV2(
DateTime startDate,
DateTime endDate,
DayOfWeek dayOfWeek,
int ordinal)
{
var foundDates = new List<DateTime>();
// Make sure ordinal parameter is within the allowable range
//If it's too high, set it to 5 so it returns the last
// qualifying day of each month
ordinal = Math.Min(Math.Max(ordinal, 1), 5);
while (startDate < endDate)
{
int month = startDate.Month;
//Set workingDate to the first day of the month.
var workingDate = new DateTime(startDate.Year, month, 1);
//Set workingDate to the first occurrence of the DayOfWeek parameter
workingDate = (int)workingDate.DayOfWeek > (int)dayOfWeek
? workingDate.AddDays(7 - (int)workingDate.DayOfWeek + (int)dayOfWeek)
: workingDate.AddDays((int)dayOfWeek - (int)workingDate.DayOfWeek);
//Advance the date by the number of days required to satisfy the ordinal parameter
workingDate = workingDate.AddDays((ordinal - 1) * 7);
//If the date has crossed the month boundary, step back a week.
//So the last occurrence of the target day is returned
workingDate = workingDate.Month != month ? workingDate.AddDays(-7) : workingDate;
foundDates.Add(workingDate);
startDate = startDate.AddMonths(1);
}
return foundDates;
}
Using the Code
Set the ordinal parameter to the occurrence in the month for the day of the week you require. So it's set to 1 for the first, 2 for the second, etc. If you enter 5 and there are not 5 occurrences in a particular month, you will get the date of the last occurrence in that month. Here's an example that returns the date of every second Friday of the month in 2016.
private static void Main()
{
//Example, to get the date of every second Friday in the month for 2016
DateTime beg = DateTime.Parse("01/01/2016");
DateTime end = DateTime.Parse("01/01/2017");
List<DateTime> SecondFridays = GetDatesByOrdinalDayV2(beg, end, DayOfWeek.Friday, 2);
var dateStrings = SecondFridays
.Select(dateTime => dateTime.ToString("MMMM dd, yyyy")).ToList();
File.WriteAllLines(@"C:\Temp\DateTest.txt", dateStrings);
//writes
//January 08, 2016
//February 12, 2016
//March 11, 2016
//April 08, 2016
//May 13, 2016
//June 10, 2016
//July 08, 2016
//August 12, 2016
//September 09, 2016
//October 14, 2016
//November 11, 2016
//December 09, 2016
}