Click here to Skip to main content
15,881,424 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
24 Feb 2016CPOL 11.9K   2   4
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

C#
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.

C#
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
       }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNice! Pin
Maciej Los1-Jun-16 1:37
mveMaciej Los1-Jun-16 1:37 
AnswerRe: Nice! Pin
George Swan1-Jun-16 2:36
mveGeorge Swan1-Jun-16 2:36 
QuestionNice improvement/elegantation! Pin
B. Clay Shannon24-Feb-16 4:56
professionalB. Clay Shannon24-Feb-16 4:56 
AnswerRe: Nice improvement/elegantation! Pin
George Swan24-Feb-16 5:56
mveGeorge Swan24-Feb-16 5:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.