Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: DateTime - Going through a period of days?

I have a period of days and I want to go through it and execute the same code on each date.

begin and end are DateTime format with difference of a month at least

while ( !(begin.Equals(end)) )
        {
           ...some code here...              
           begin = begin.AddDays(1);
        }
  1. I'm not sure if it automatically upgrades the Month value when the Day value reaches the end of an exact month(in exact year) - for example February doesn't have always the same amount of days so...

  2. Is there a better/shorter/nicer way of increasing the date by one day? For example something like this: begin.Day++; or this: begin++; ?

I'm not used to C# yet so sorry for asking this lame question and thank you in advance for any answer.

like image 663
Ms. Nobody Avatar asked Mar 24 '23 05:03

Ms. Nobody


1 Answers

1) Yes it does. All date arithmetic is handled correctly for you.

2) Yes there is. You can do:

var oneDay = TimeSpan.FromDays(1);
...
begin += oneDay;

You could also use a for loop:

var oneDay = TimeSpan.FromDays(1);

for (DateTime currentDay = begin; currentDay < end; currentDay += oneDay)
{
    // Some code here.
}

One final thing: If you want to be sure to ignore the time component, you can ensure that the time part of the begin and end dates is set to midnight as follows:

begin = begin.Date;
end   = end.Date;

Make sure you have your bounds correct. The loop goes while currentDay < end - but you might need currentDay <= end if your time range is inclusive rather than exclusive.

like image 84
Matthew Watson Avatar answered Apr 02 '23 09:04

Matthew Watson