Calculating recurrence of events using DateTime in C#

无人久伴 提交于 2019-12-11 10:09:41

问题


I have a set of events that reoccur. I need to be able to calculate when these events occur with the next 5 weeks or so.

This system will inform the user that within this month, these events will occur..

For example:

Event1

  • Date Started = Monday 19th Dec 2011
  • Recurrence Pattern = Monday/Fortnightly

Event2

  • Date Started = Thursday 3rd Feb 2012
  • Recurrence Pattern = Thursday/Every Three Weeks

It's now 22 March - within the next 5 weeks what dates will Events 1 & 2 fall on.

It would also be useful to be able to detect if it's Xmas then the event will fall onto another day.

I'm using .NET MVC2 but I guess that's incidental.

Thanks for any assistance


回答1:


Something like this should do the trick:

//enum for various patterns
public enum OccurrenceRate
{
    Weekly,
    Fortnightly,
    Monthly
}

public static List<DateTime> GetOccurrences(DateTime startDate, DateTime endDate, OccurrenceRate rate)
{
    List<DateTime> occurrences = new List<DateTime>();

    var nextDate = startDate;

    while (true)
    {
        if (nextDate <= endDate)
        {
            occurrences.Add(nextDate);
        }
        else
        {
            break;
        }

        switch (rate)
        {
            case OccurrenceRate.Weekly:
            {
                nextDate = nextDate.AddDays(7);
                break;
            }
            case OccurrenceRate.Fortnightly:
            {
                nextDate = nextDate.AddDays(14);
                break;
            }
            case OccurrenceRate.Monthly:
            {
                nextDate = nextDate.AddMonths(1);
                break;
            }
        }
    }

    return occurrences;
}

Example of calling code:

DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddDays(35); //5 weeks

var dates = GetOccurrences(startDate, startDate.AddDays(35), OccurrenceRate.Weekly);
dates.ForEach(date =>
{
    Console.WriteLine("{0:yyyy-MM-dd}", date);
});



回答2:


You should probably just use the DateTime.AddDays method:

var date = new DateTime(2011, 12, 19);
var end = new DateTime(2012, 4, 26); // five weeks from now
while (date < end)
{
    if (date > DateTime.Now)
    {
        // This is a date you want
    }
    date = date.AddDays(14);
}


来源:https://stackoverflow.com/questions/9821511/calculating-recurrence-of-events-using-datetime-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!