In my project, I need to calculate the dates of repeated events. First I have a start date / time and information on how this event should be repeated:
Every Day Every Week Every 2 Weeks Every 3 Weeks Every Month Every 2 Months ...
What is the right way to do this? It should work correctly with different time zones and daytime settings. I think I should just add the days / weeks / month to the local DateTime and then convert it to UTC. But I'm not so sure about that. What happens if I add a few days, and it will be a time when we need to set our clocks forward one hour. In this case, this time will not be.
Below is the code I wrote, but I'm not sure if it works correctly in each case:
private static List<DateTime> FindOccurrences(DateTime localStart, Repeat repeat, int occurrences) { var result = new List<DateTime> { localStart }; switch (repeat) { case Repeat.Daily: for (int i = 1; i <= occurrences; i++) result.Add(localStart.AddDays(i)); break; case Repeat.Every2Weeks: for (int i = 1; i <= occurrences; i++) result.Add(localStart.AddDays((7 * 2) * i)); break; ... } return result; } public List<Event> CreateRepeating(string timeZone, Repeat repeat, int repeatEnds, DateTime localStart, int eventDuration) { var events = new List<Event>(); var occurrences = FindOccurrences(localStart, repeat, repeatEnds); foreach (var occurrence in occurrences) { var item = new Event(); item.Start = occurrence.ToUtcTime(timeZone); item.End = occurrence.ToUtcTime(timeZone).AddMinutes(eventDuration); events.Add(item); } return events; }
PS: All dates are stored in UTC format in the database.
source share