2013-07-08 62 views
0

在這裏,我需要得到給定日期範圍內的星期日。當我給出日期範圍時, SelectedStartDate是2013年7月1日& SelectedEndDate是7/31/2013,那麼這段代碼返回星期日是7/2,7/9,7/16,7/23,7/30但我的預期日期是7/7,7/14,7/21,7/28尋找日期範圍內的具體日期

static IEnumerable<DateTime> SundaysBetween(DateTime SelectedStartDate, DateTime SelectedEndDate) 
    { 

     DateTime current = SelectedStartDate; 

     if (DayOfWeek.Sunday == current.DayOfWeek) 
     { 

      yield return current; 
     } 
     while (current < SelectedEndDate) 
     { 

      yield return current.AddDays(1); 

      current = current.AddDays(7); 
     } 

     if (current == SelectedEndDate) 
     { 

      yield return current; 
     } 

    } 
} 
+0

問題是什麼?你有什麼問題? – Amy

+1

@Amy錯誤的日期返回 – TechGuy

回答

4
static IEnumerable<DateTime> SundaysBetween(DateTime startDate, DateTime endDate) 
{ 
    DateTime currentDate = startDate; 

    while(currentDate <= endDate) 
    { 
     if (currentDate.DayOfWeek == DayOfWeek.Sunday) 
      yield return currentDate; 

     currentDate = currentDate.AddDays(1); 
    }   
} 
1

這可以完成很容易使用AddDays,而不會過度複雜的問題。這裏有一個小片段,我寫證明:

// Setup  
DateTime startDate = DateTime.Parse("7/1/2013"); 
DateTime endDate = DateTime.Parse("7/31/2013"); 

// Execute 
while (startDate < endDate) 
{ 
    if (startDate.DayOfWeek == DayOfWeek.Sunday) 
    { 
     yield return startDate; 
    } 
    startDate = startDate.AddDays(1); 
} 
3
public IEnumerable<DateTime> SundaysBetween(DateTime start, DateTime end) 
    { 
     while (start.DayOfWeek != DayOfWeek.Sunday) 
      start = start.AddDays(1); 

     while (start <= end) 
     { 
      yield return start; 
      start = start.AddDays(7); 
     } 
    } 
+1

+1非常好的解決方案 –