In my project I need to calculate dates for repeating events. At the beginning I just have a start date/time and the information how this event must repeat:
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 day saving time settings. I think I should just add days/weeks/month to the local DateTime and then convert it to UTC. But I'm not sure about this. What happens if I add a few days and this will be the time when we need to adjust our clocks forward one hour. In this case this time will not exists.
Below is the code I wrote, but I'm not sure that it works correctly in every 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…