Click here to Skip to main content
15,888,461 members
Articles / Programming Languages / C#
Article

Recurring Date Generator with Pattern Coding

Rate me:
Please Sign up or sign in to vote.
4.95/5 (51 votes)
4 Sep 2007CPOL4 min read 146.3K   6.9K   98   44
Create recurring dates using a user-defined pattern. Create recurring dates from a coded value that defines what the pattern should be.
Screenshot - ScreenShot01.png

Introduction

I needed a way to create recurring dates using a given pattern of dates such as every weekday, every Saturday and Monday, etc. I couldn't find any sample code on the web other than what you can purchase, so I made this library.

This library not only creates recurring dates but it also returns a coded value that you can store to at a later date, create the same recurring date pattern and adjust the values as needed. This ability to alter the pattern or add more dates to the end of the returned values is what I consider to be a real world requirement. Creating recurring dates is not the issue when creating a pattern of dates, it's being able to store that pattern's design value so it can be used to alter the dates at a later date.

Using the coded pattern value, or Series Info as I call it in this article, you can edit appointment dates similar to those found in Microsoft Outlook. When editing an event in Outlook, you're asked if this is for the current date or the entire series. If you don't have the series date format pattern it's impossible to load up the date controls in the correct format so they match what you first used when you created the recurring dates. This library gives you the ability to do this using the Series Info returned value.

Background

I needed a way to create recurring dates and be able to edit them or adjust the values at a later date.

Using the code

You can open the source solution for a complete sample application that uses the RecurrenceGenerator assembly.

The RecurrenceGenerator library exposes Daily, Weekly, Monthly, and Yearly RecurrenceSettings classes that inherit from RecurrenceSettings class. All the classes have the same constructors.

The constructors allow for:

  1. Start Date (No ending date)
  2. Start Date, End Date (defined ending date)
  3. Start Date, Number of Occurrences (create only x-number of dates)

The constructors are constructed in such a way that you have to, at a minimum, give a Start Date.

C#
/// <summary>
/// Get dates by Start date only. This is for no ending date values.
/// </summary>
/// <param name="startDate"></param>
public DailyRecurrenceSettings(DateTime startDate) : base(startDate) { }

/// <summary>
/// Get dates by Start and End date boundaries.
/// </summary>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
public DailyRecurrenceSettings(DateTime startDate, DateTime endDate) : 
         base(startDate, endDate) { }

/// <summary>
/// Get dates by Start date and number of occurrences.
/// </summary>
/// <param name="startDate"></param>
/// <param name="numberOfOccurrences"></param>
public DailyRecurrenceSettings(DateTime startDate, int numberOfOccurrences) : 
         base(startDate, numberOfOccurrences) { }

The dates are returned in an object called RecurrenceValues. This object is returned by making a call to GetValues([various params based on type of RecurrenceSettings]).

Once the dates are returned, you can use them to list the values such as those in the sample application.

Screenshot - ScreenShot02.png

This workspace shows the dates that were generated by the previous tabs date pattern. The "Series Info" readonly text box shows you the return value that you would store with each date event in your application. Storing this value allows you to create the next date in the pattern as well as generate all the values and adjust them as needed.

Screenshot - ScreenShot05.png

This tab of the sample application allows you to adjust the original Series Info value and create a new set of values. This is the real world in that you may need to extend the date values you're looking at in your calendar control. You might also need to show the next date for the month that's being viewed in your UI control in Winforms.

This third tab allows you to adjust:

  • Start Date
  • Number of occurrences
  • End Date
  • View the definition of the Series Info value. See screen below for example.
Screenshot - ScreenShot06.png

Clicking the "Def." button will bring up a viewer to explain what each Series Info value means. The definitions are different for each pattern (daily, weekly, monthly, yearly).

Screenshot - ScreenShot04.png

This tab shows you the object that can be returned by passing in the Series Info into the RecurrenceHelper shared function GetFriendlySeriesInfo(string seriesInfo).

The Series Info value is different for each date pattern type such as daily, weekly, etc. Each RecurrenceSettings class has a method to view the breakdown of the coded value. This is reached by a call to the RecurrenceHelper.GetPatternDefinition(string seriesInfo).

Points of Interest

Making the sample application helped in the testing process of the date generation. Making a prototype was a good tool to ensure that the RecurrenceGenerator library created the correct values.

History

  • 7 September, 2007: Added the ability to return a modified series of dates using an existing Series Info value and modified Start Date

License

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


Written By
Software Developer (Senior) BOCA Software Technologies, Inc.
United States United States
.NET Developer in Garner, North Carolina. Specializing in WinForms development in C#, VB.Net.

CEO/Founder BOCA Software Technologies, Inc.

Comments and Discussions

 
QuestionGreat works! Pin
Kingsten Koh25-Feb-22 21:18
Kingsten Koh25-Feb-22 21:18 
PraiseAwsome Pin
IDstrife6-Mar-19 6:11
IDstrife6-Mar-19 6:11 
BugRecurring Date Generator with Pattern Coding not Working on Saturday Pin
Member 1385371331-May-18 16:44
Member 1385371331-May-18 16:44 
GeneralMy vote of 5 Pin
Khalil-Salah16-Aug-17 21:30
Khalil-Salah16-Aug-17 21:30 
QuestionGet Position of SIngle Event Date Pin
JoeJoe8757716-May-16 21:07
JoeJoe8757716-May-16 21:07 
AnswerRe: Get Position of SIngle Event Date Pin
Garth J Lancaster16-May-16 21:53
professionalGarth J Lancaster16-May-16 21:53 
GeneralRe: Get Position of SIngle Event Date Pin
JoeJoe8757716-May-16 22:14
JoeJoe8757716-May-16 22:14 
QuestionAnyone still working with this? Anyone know of any bug since last release? Pin
Kebrite28-Jul-15 4:11
Kebrite28-Jul-15 4:11 
GeneralMy vote of 5 Pin
NisHtRk15-Feb-14 4:15
NisHtRk15-Feb-14 4:15 
GeneralMy vote of 5 Pin
Norbert Haberl27-Jan-14 1:32
Norbert Haberl27-Jan-14 1:32 
GeneralGreat Concept Pin
Raavis12-Aug-13 23:47
Raavis12-Aug-13 23:47 
QuestionExecellent !!!! Pin
Member 194328324-Jul-13 23:32
Member 194328324-Jul-13 23:32 
GeneralMy vote of 5 Pin
Member 194328324-Jul-13 23:30
Member 194328324-Jul-13 23:30 
QuestionHow can I set the time Pin
LozGemachet19-Jun-13 7:30
LozGemachet19-Jun-13 7:30 
QuestionDoes this project work with web based applications Pin
ochiha_ita19-Oct-12 6:16
ochiha_ita19-Oct-12 6:16 
Questionrecur weekly not working Pin
Shivapragasam17-Jun-12 19:58
Shivapragasam17-Jun-12 19:58 
AnswerRe: recur weekly not working Pin
Andy T.N. Powell3-Aug-12 3:28
Andy T.N. Powell3-Aug-12 3:28 
This bug occurs because the method GetNextDay() in the WeeklyRecurrenceSettings class increments the date by the recurring week value (regenEveryXWeeks) number of weeks every time the date gets to a Saturday but ONLY when a Saturday isn't one of your selected recurring days. When you've got a Saturday selected as a recurring day, it merely adds the date to the recurring date collection back in the calling method GetEveryXWeeksValues() and incremements the date to the day after.

I've fixed this by updating GetNextDay() to first check if the date being passed in to the method is a Saturday and then straight away incremementing it by the recurring week value if and only if we've already saved at least one Saturday to our collection. This is because in the very first week you look at you don't want to increment the date by X weeks until after you've checked (and selected) your first Saturday. To do this I had to create a class level private int "counter" variable which is incremented everytime a Saturday is saved to the recurring date collection.

C#
int selectedSaturdayCount = 0;


C#
<pre>  DateTime GetNextDay(DateTime input)
        {
            DateTime? returnDate = null;

            // Get the return date by incrementing the date
            // and checking the value against the selected days
            // of the week.
            do
            {
                //BUG FIX: 03/08/2012 : A.Powell : Fix issue around recurring Saturdays
                //If we've just finished a single week (ie. last day was a Saturday) 
                //AND are selecting Saturdays then increment the date by Weekly 
                //Occurrence value number of days so that we're looking in the
                //correct next appropriate week ... but MUST ensure that we only do 
                //this after at least one Saturday has been selected ie. we've
                //finished checking the first week, which may be a Partial week
                if (input.DayOfWeek == DayOfWeek.Saturday && selectedSaturdayCount > 0)
                {
                    input = input.AddDays((regenEveryXWeeks - 1) * 7);
                }
                input = input.AddDays(1);

                switch (input.DayOfWeek)
                {
                    case DayOfWeek.Monday:
                        if (selectedDays.Monday)
                            returnDate = input;
                        break;
                    case DayOfWeek.Tuesday:
                        if (selectedDays.Tuesday)
                            returnDate = input;
                        break;
                    case DayOfWeek.Wednesday:
                        if (selectedDays.Wednesday)
                            returnDate = input;
                        break;
                    case DayOfWeek.Thursday:
                        if (selectedDays.Thursday)
                            returnDate = input;
                        break;
                    case DayOfWeek.Friday:
                        if (selectedDays.Friday)
                            returnDate = input;
                        break;
                    case DayOfWeek.Saturday:
                        if (selectedDays.Saturday)
                        {
                            returnDate = input;
                            selectedSaturdayCount += 1;
                        }
                        else
                        {
                            // Increment by weeks if regenXWeeks has a value 
                            // greater than 1 which is default.
                            // But only increment if we've gone over
                            // at least 7 days already.
                            if (regenEveryXWeeks > 1)
                                input = input.AddDays((regenEveryXWeeks - 1) * 7);
                        }
                        break;
                    case DayOfWeek.Sunday:
                        if (selectedDays.Sunday)
                            returnDate = input;
                        break;
                }
            } while (!returnDate.HasValue);
            return returnDate.Value;
        }



In fact, if you look at Microsoft Outlook (which I believe this is mostly replicating), it appears to use Sunday as the day to increment the weekly recurrence, so you could just update GetNextDay() to carry out the relevant checks on the Sunday rather than the Saturday. I've tested this to some degree by running identical tests creating Recurring Appointments in MS Outlook and this Recurrence Tester front-end and it all seems to match exactly.
GeneralRe: recur weekly not working Pin
erozenblat22-Oct-13 22:43
erozenblat22-Oct-13 22:43 
GeneralRe: recur weekly not working Pin
Zokrit31-Oct-13 4:50
Zokrit31-Oct-13 4:50 
GeneralIs there a newer Version which works with EndDateType.NoEndDate ? Pin
Bombias15-Apr-11 1:48
Bombias15-Apr-11 1:48 
GeneralDate pattern not working correctly for week days Pin
max carter23-Dec-09 23:23
max carter23-Dec-09 23:23 
GeneralRe: Date pattern not working correctly for week days Pin
Victor Boba24-Dec-09 3:00
Victor Boba24-Dec-09 3:00 
GeneralRe: Date pattern not working correctly for week days Pin
max carter25-Dec-09 19:01
max carter25-Dec-09 19:01 
GeneralIt's very nice. Pin
iamnon26-May-09 6:32
iamnon26-May-09 6:32 
GeneralGood coding Pin
TomChris24-Oct-08 12:11
TomChris24-Oct-08 12:11 

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.