在这里,我需要在给定的日期范围内获得星期日。当我给出日期范围时, SelectedStartDate是2013年7月1日& SelectedEndDate是2013年7月31日然后这个代码返回星期日是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 :(得分: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 :(得分: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);
}
}
答案 2 :(得分: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);
}