简体   繁体   English

C#在日期上向后迭代

[英]C# iterate backwards over date

I am looking for a C# solution that will allow me to iterate backwards over a date. 我正在寻找一种C#解决方案,该解决方案将允许我在日期上向后迭代。 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. 当然,它应该能够检测到月份何时更改或是a年等,并以MM-DD-YYYY格式返回日期。

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. 您可以使用Dateadd函数,该函数使您可以在日期中增加或减少时间间隔,并返回结果日期。 In your case, the interval is "d" (day). 在您的情况下,间隔为“ d”(天)。 See here . 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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