简体   繁体   中英

C# iterate backwards over date

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.

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");
}
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"));
}

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"));
        }


    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM