Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

Do it this way (don't compare for equality, because hours may be different and the loop goes forever).

    while ( begin <= end )
    {
       ...some code here...              
       begin = begin.AddDays(1);
    }

You could try this, which I think is a little more succinct:

while (DateTime.Compare(begin, end) < 0)
{
    /* Some code here */
    begin = begin.AddDays(1);
}

The DateTime object knows how to increment months, years, etc. as appropriate, so you needn't worry about that.

The code you've posted is correct and should work fine. And don't worry, the AddDays method will automatically increment the month and the year when necessarry.

You can also use a for loop if you find it more readable:

for (DateTime date = startDate; date < endDate; date = date.AddDays(1))
{
    // Your code here
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top