I am trying to iterate in a range of dates, I get everything correct if I enter from a month below to the current one:
Example from 08-1-2022 to 09-14-2022, for that use the following code:
DateTime Fecini = new DateTime(2022, 8, 1);
DateTime FecFinal = new DateTime(2022, 9, 14);
System.TimeSpan dif = FecFinal - Fecini;
DateTime FecSec;//fecha seleccionad en el bucle
for (int n = 0; n <=dif.Days; n++)
{
FecSec = Fecini.AddDays(n);
Console.WriteLine(FecSec);
}
It prints correctly, but what I want is for it to be from today to last month (09-14-2022 to 08-01-2022), I use the following code but the problem is that it does not stop on the 1st of the month August, continues and continues to print more dates.
I hope you can support me with it or support me where my mistake is to correct it.
DateTime Fecini = new DateTime(2022, 9, 14);
DateTime FecFinal = new DateTime(2022, 8, 1);
System.TimeSpan dif = Fecini - FecFinal;
DateTime FecSec;
for (int n = 0; n <= dif.Days; n--)
{
FecSec = Fecini.AddDays(n);
Console.WriteLine(FecSec);
}
Sometimes you forget that a for can iterate over elements other than an integer. It seems more readable to me to do it as follows:
In reverse order:
Try like this:
I was telling you negatives, that's why the condition was never met
n <= dif.Days
andn
it was always going to be less