2016-08-30 205 views
0

我有月,年,星期幾和星期幾,基於我想得到一個日期。我怎樣才能做到這一點?以下是我的代碼,但我沒有得到正確的結果。如何從年,月,星期幾和星期幾獲取日期? C#

我在這裏錯過了什麼?

代碼:

internal DateTime? GetDate(int year) // year = 2016 
{ 
    int month; 
    DateTime? date; 

    switch (Type) 
    { 
     case "CALCULATED": 
      month = FixedMonth; // month = 9 
      var firstDayOfWeek = new DateTime(year, month, 1); // firstDayOfWeek = 9/1/2016 12:00:00 AM 
      while (RestaurantSchedule.GetOneBasedDayOfWeek(firstDayOfWeek) <= DayOfWeek) // DayOfWeek = Monday 
      { 
       firstDayOfWeek = firstDayOfWeek.AddDays(1); 
      } 
      date = firstDayOfWeek.AddDays((WeekOfMonth - 1) * 7); // WeekOfMonth = 1, returns date = 9/1/2016 12:00:00 AM 
      if (date.Value.Month > month) 
      { 
       return date.Value.AddDays(-7); 
      } 
      return date; 
     default: 
      return new DateTime?(); 
    } 
} 

public static OneBasedDayOfWeek GetOneBasedDayOfWeek(DateTime date) // date = 9/1/2016 12:00:00 AM 
{ 
    // returns Thursday 
    return (OneBasedDayOfWeek)Enum.Parse(typeof(OneBasedDayOfWeek), date.DayOfWeek.ToString()); 
} 

// OneBasedDayOfWeek uses following enum   
public enum DayOfWeek 
{ 
    None = 0, 
    Sunday = 1, 
    Monday = 2, 
    Tuesday = 3, 
    Wednesday = 4, 
    Thursday = 5, 
    Friday = 6, 
    Saturday = 7 
} 

數據庫條目:

HolidayDefinitionId Type   FixedMonth FixedDay DayOfWeek WeekOfMonth Adjustment HolidayName  Enabled 
-------------------- ------------ ----------- ----------- ----------- ----------- ----------- --------------- ------- 
LABOR     CALCULATED 9   0   2   1   0   Labor Day  1 
PRESIDENTS   CALCULATED 2   0   2   3   0   President's Day 1 

實際結果:

Presidents Day = 02/15/2016 
Labor Day = 09/01/2016 

預期結果:

Presidents Day = 02/16/2016 
Labor Day = 09/05/2016 
+0

是'WeekOfMonth'不夠好界定?勞動節「的第一個星期一」在九月。如果9月一個星期二開始,那麼勞動節是在那個月的第二個星期,不是嗎?但是如果一年九月從星期日開始,那將是本月的第一週。 – Quantic

+0

什麼是OneBasedDayOfWeek? – Kolichikov

+0

@Kolichikov'使用OneBasedDayOfWeek = KI.TAS.DomainObjects.Day.DayOfWeek;'基本上使用所聲明的枚舉值。 – CSharper

回答

1

今年的總統日是在2月15日,所以這是正確的。 我得到了這樣的勞動節: 對於第一部分,我不得不假設你想將微軟DateTime(星期日= 0)翻譯成你的Sunday = 1枚舉。

public static DayOfWeek GetOneBasedDayOfWeek(DateTime date) // date = 9/1/2016 12:00:00 AM 
    { 
     // returns Thursday 
     return (DayOfWeek)((int)date.DayOfWeek + 1); 
    } 

而在你的主要功能,你想迭代,直到你實際上已經達到了你一週中的哪一天,不只是當它是以下(一旦你達到星期天,你的循環就會停止,因爲(int)Sunday < (int)AnyOtherDay

while (GetOneBasedDayOfWeek(firstDayOfWeek) != DayOfWeek) 

我的日期幾年的道路測試,這和它似乎工作。

+0

也適用於我。我嘗試了剩餘的假期,並獲得確切的價值。 – CSharper