0

在这里我需要在给定的日期范围内获取星期日。当我给出日期范围时,SelectedStartDate 是 7/1/2013 和 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;
        }

    }
}
4

3 回答 3

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);
    }         
}
于 2013-07-08T16:45:31.980 回答
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);
        }
    }
于 2013-07-08T16:46:08.387 回答
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);
}
于 2013-07-08T16:45:06.067 回答