2013-03-21 34 views
-3

我有任務重複出現,我正在構建一些能夠自動爲我重新創建的任務。找到下一個再錄製日期

我有這樣的枚舉:

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對象?

我需要EX:

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... 
} 

感謝

+0

那麼這個問題有什麼問題:/ – user2043533 2013-03-21 14:30:06

+0

試着弄清楚你的問題的更好的解釋。目前還不清楚 – 2013-03-21 14:31:08

+1

[神聖記錄蝙蝠俠!](http://msdn.microsoft.com/en-us/library/system.datetime_methods.aspx)AddDays,AddMonths,... – 2013-03-21 14:37:33

回答

3

這是一個硬編碼解決方案,但如果你能提供更通用的條件下,它會更容易做出更好的東西:

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警告。與你想要的唯一細微的區別是,日期不會轉移到下個月,但騎自行車保留。

+0

不完全,請參閱關於二月份的警告... – user2043533 2013-03-21 14:40:52

+0

是的,您在我的回答後更新了問題。我必須考慮更好的解決方案。 – 2013-03-21 14:42:52

+0

@ user2043533你是什麼意思「不完全」?你認爲AddMonths是如此破碎是否會給你不存在的日期? – MikeSmithDev 2013-03-21 14:55:48

相關問題