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);
}
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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With