1

我有一组重复发生的事件。我需要能够计算出这些事件在接下来的 5 周左右发生的时间。

本系统将通知用户,在本月内,将发生这些事件。

例如:

事件1

  • 开始日期= 2011 年 12 月 19 日星期一
  • 重复模式= 星期一/两周一次

事件2

  • 开始日期= 2012 年 2 月 3 日星期四
  • 重复模式= 星期四/每三周

现在是 3 月 22 日——在接下来的 5 周内,事件 1 和 2 的日期是什么。

能够检测是否是圣诞节也很有用,那么活动将推迟到另一天。

我正在使用.NET MVC2,但我想这是偶然的。

感谢您的帮助

4

2 回答 2

3

这样的事情应该可以解决问题:

//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;
}

调用代码示例:

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);
});
于 2012-03-22T11:50:56.677 回答
2

您可能应该只使用以下DateTime.AddDays方法:

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);
}
于 2012-03-22T11:41:07.860 回答