【问题标题】:Finding the next date of reoccurance [closed]寻找下一个再次发生的日期[关闭]
【发布时间】:2013-03-21 14:28:27
【问题描述】:

我有重复发生的任务,我正在构建一些会自动为我重新创建它们的东西。

我有这个枚举:

  public enum Periods {
      Day = 0, //every day
      Week = 1, //every week...
      BiWeek = 2, //every 2nd week
      Month = 3,
      BiMonth = 4, 
      Year = 5
  };

我需要能够在这些间隔内重新创建。

因此,我可能会在每个月的 29 日重复发生一些事情。如果 29 日不存在,比如 2 月,那么它应该跳到下一个最好的时间,即 3 月 1 日。

是否有算法可以做到这一点,可能使用 DateTime 对象?

我需要前任:

DateTime GetNextOccurrence(DateTime initialDate, DateTime lastOccurrence, Periods p)
{
   if(p == Day)
    return lastOccurance.addDays(1);
   else if (p == Month)
   {
      add 1 month to last occurance month then start at day 1 of the month and keep adding days until it gets as close as possible...
}

谢谢

【问题讨论】:

  • 那么这个问题有什么问题:/
  • 试着找出一个更好的解释你的问题。不清楚
  • Holy documentation Batman! AddDays, AddMonths, ...
  • 也许 DDay.iCal 库可以提供帮助。
  • 我无法理解initialDate 的作用?

标签: c# asp.net date


【解决方案1】:

这是一个硬编码解决方案,但如果您提供更通用的条件,则更容易改进:

private static DateTime GetNextOccurrence(DateTime initialDate, 
                                          DateTime lastOccurrence, 
                                          Periods p)
{
    switch (p)
    {
        case Periods.Day: return lastOccurrence.AddDays(1);
        case Periods.Week: return lastOccurrence.AddDays(7);
        case Periods.BiWeek: return lastOccurrence.AddDays(14);
        case Periods.Month:
        case Periods.BiMonth:
          {
              DateTime dt = lastOccurrence.AddMonths(p == Periods.Month ? 1 : 2);
              int maxDays = DateTime.DaysInMonth(dt.Year, dt.Month);
              int days = Math.Min(initialDate.Day, maxDays);
              return new DateTime(dt.Year, dt.Month, days);
          }
        case Periods.Year: return lastOccurrence.AddYears(1);
        default: return lastOccurrence;
    }
}

更新后的版本更加有编码,但我更新了代码以解决AddMonth 警告。与您想要的唯一细微差别是日期不会转移到下个月,但会保留循环。

【讨论】:

  • 不完全是,请参阅关于 2 月的警告......
  • 是的,您在我回答后更新了问题。我必须考虑更好的解决方案。
  • @user2043533 “不完全”是什么意思?你认为 AddMonths 如此糟糕以至于会给你不存在的日期?
  • 不,但是假设它必须在每个月的 29 日发生,addMonths 会将您带到 3 月 1 日,但下个月应该是 3 月 29 日,而不是 4 月 1 日...
  • @user2043533 这就是为什么您将Months 添加到原始日期...好的,您是对的,我知道他的回答存在问题。
猜你喜欢
  • 1970-01-01
  • 2012-10-30
  • 2012-03-01
  • 2016-08-26
  • 2011-02-19
  • 2017-01-21
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
相关资源
最近更新 更多