Reputation: 4560
In here i need to get Sundays in given date range.When i give the date range, SelectedStartDate is 7/1/2013 & SelectedEndDate is 7/31/2013 then this code returns Sundays are 7/2,7/9,7/16,7/23,7/30 But my expect dates are 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;
}
}
}
Upvotes: 0
Views: 82
Reputation:
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);
}
}
Upvotes: 3
Reputation: 236208
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);
}
}
Upvotes: 4
Reputation: 32258
This can be accomplished pretty easily using AddDays
without over complexing the issue too much. Here's a short snippet I wrote to demonstrate:
// 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);
}
Upvotes: 1