Reputation: 5845
I am looking for a C# solution that will allow me to iterate backwards over a date. Starting at the current date or provided date I would like to loop over the date subtracting one day each time through the loop for a given number of days. It should of course be able to detect when the month has changed or it is a leap year etc., and return the date in MM-DD-YYYY format.
Upvotes: 2
Views: 1860
Reputation: 116168
public IEnumerable<DateTime> Dates(int nDays)
{
DateTime dt = DateTime.Now;
yield return dt;
for(int i=0;i<nDays-1;i++)
{
dt = dt.AddDays(-1);
yield return dt;
}
}
foreach (var dt in Dates(10))
{
Console.WriteLine(dt.ToString("MM-dd-yyyy"));
}
Upvotes: 2
Reputation: 5213
You can use Dateadd function, that let you add or subtract an interval of time to/from a date and returning the resulting date. In your case, the interval is "d" (day). See here.
Upvotes: 0
Reputation: 1407
this would iterate backwords:
class Program
{
static void Main(string[] args)
{
DateTime myDate = DateTime.Now;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(myDate.AddDays(-i).ToString("MM-dd-yyyy"));
}
}
}
Upvotes: 1
Reputation: 60714
Should be easy enough:
var givenNumberOfDays = 30;
for( DateTime day = DateTime.Now; day > DateTime.Now.AddDays( -givenNumberOfDays); day = day.AddDays(-1) )
{
//perform your logic here
var dateInCorrectFormat = day.ToString("MM-dd-yyyy");
}
Upvotes: 6