Thursday, April 28, 2011

C#: Iterate over each Day between StartDate and EndDate

I have a DateTime StartDate and EndDate.

How can I, irrespective of times, iterate across each Day between those two?

Example: StartDate is 7/20/2010 5:10:32 PM and EndDate is 7/29/2010 1:59:12 AM.

I want to be able to iterate across 7/20, 7/21, 7/22 .. 7/29.

Help?

From stackoverflow
  • for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
    {
        ...
    }
    

    The .Date is to make sure you have that last day, like in the example.

    Dean Harding : I think you want `date.Date <= EndDate.Date` so that you get the final day.
    corvuscorax : This goes into an infinite loop, the AddDays method doesn't change date, but returns a new DateTime instance. Use date = date.AddDays(1) instead.
    Yuriy Faktorovich : @Dean: Thanks, saw your comment after change.
  • DateTime date = DateTime.Now;
    DateTime endDate = date.AddDays(10);
    
    while (date < endDate)
    {
      Console.WriteLine(date);
      date = date.AddDays(1);
    }
    
  • You have to be careful about end-date. For example, in

    "

    Example: StartDate is 7/20/2010 5:10:32 PM and EndDate is 7/29/2010 1:59:12 AM. I want to be able to iterate across 7/20, 7/21, 7/22 .. 7/29.

    "

    date < endDate will not include 7/29 ever. When you add 1 day to 7/28 5:10 PM - it becomes 7/29 5:10 PM which is higher than 7/29 2 AM.

    if that is not what you want then I'd say you do

    for (DateTime date = start.Date; date <= end.Date; date += TimeSpan.FromDays(1))
    {
         Console.WriteLine(date.ToString());
    }
    

    or something to that effect.

0 comments:

Post a Comment