How do I loop through a date range?

onekidney

I'm not even sure how to do this without using some horrible for loop/counter type solution. Here's the problem:

I'm given two dates, a start date and an end date and on a specified interval I need to take some action. For example: for every date between 3/10/2009 on every third day until 3/26/2009 I need to create an entry in a List. So my inputs would be:

DateTime StartDate = "3/10/2009";
DateTime EndDate = "3/26/2009";
int DayInterval = 3;

and my output would be a list that has the following dates:

3/13/2009 3/16/2009 3/19/2009 3/22/2009 3/25/2009

So how the heck would I do something like this? I thought about using a for loop that would iterate between every day in the range with a separate counter like so:

int count = 0;

for(int i = 0; i < n; i++)
{
     count++;
     if(count >= DayInterval)
     {
          //take action
          count = 0;
     }

}

But it seems like there could be a better way?

mqp

Well, you'll need to loop over them one way or the other. I prefer defining a method like this:

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
    for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
        yield return day;
}

Then you can use it like this:

foreach (DateTime day in EachDay(StartDate, EndDate))
    // print it or whatever

In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3) in the loop instead of AddDays(1).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related