2013-07-01 81 views
0

我想要使用下面的代碼獲取所有工作日。在asp.net中選擇工作日日曆以編程方式

private List<DateTime> getWeekDays(DateTime dt) 
    { 
     List<DateTime> result = new List<DateTime>(); 

     int month = dt.Month; 
     dt = dt.AddDays(-dt.Day + 1);//Sets dt to first day of month 

     //Sets dt to the first week day of the month; 
     if (dt.DayOfWeek != DayOfWeek.Monday) 
      while (dt.DayOfWeek != DayOfWeek.Friday) 
       dt = dt.AddDays(1); 

     //Adds the week day and stops when next month is reached. 
     while (dt.Month == month) 
     { 
      result.Add(dt); 
      dt = dt.AddDays(dt.DayOfWeek == DayOfWeek.Friday ? 3 : 1); 
     } 
     return result; 
    } 

但是這不能正常工作。當我通過July月到getWeekDays(DateTime dt)方法時,這給正確的所有星期幾。但如果我通過AugustSemptember,上面的代碼不會返回給定月份的所有星期幾。

錯誤在哪裏?

回答

1
 private List<DateTime> getWeekDays(DateTime dt) 
     { 
      List<DateTime> result = new List<DateTime>(); 

      int month = dt.Month; 
      dt = dt.AddDays(-dt.Day + 1);//Sets dt to first day of month 

      //If dt is a weekend add days to move it to Monday (your while loop below will handle the rest) 
      if(dt.DayOfWeek == DayOfWeek.Saturday) 
      { 
       dt = dt.AddDays(2); 
      } 
      else if (dt.DayOfWeek == DayOfWeek.Sunday) 
      { 
       dt = dt.AddDays(1); 
      } 

      //Adds the week day and stops when next month is reached. 
      while (dt.Month == month) 
      { 
       result.Add(dt); 
       dt = dt.AddDays(dt.DayOfWeek == DayOfWeek.Friday ? 3 : 1); 
      } 

      return result; 
     } 
相關問題