C# 如何在两个日期之间循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1199108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:42:04  来源:igfitidea点击:

How to loop between two dates

c#datetime

提问by Goober

I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.

我有一个日历,它将选定的日期作为字符串传递给一个方法。在此方法中,我想生成从选定的开始日期开始到选定的结束日期结束的所有日期的列表,显然包括其间的所有日期,无论选定的开始日期和结束日期之间有多少天。

Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date? Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.

下面是获取日期字符串并将它们转换为 DateTime 变量的方法的开头,以便我可以使用 DateTime 计算函数。但是,我似乎无法弄清楚如何计算开始日期和结束日期之间的所有日期?显然,第一阶段是从结束日期中减去开始日期,但我无法计算其余步骤。

Help appreciated greatly,

非常感谢帮助,

kind regards.

亲切的问候。

public void DTCalculations()
{
List<string> calculatedDates = new List<string>();
string startDate = "2009-07-27";
string endDate = "2009-07-29";

//Convert to DateTime variables
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

//Calculate difference between start and end date.
TimeSpan difference =  end.Subtract(start);

//Generate list of dates beginning at start date and ending at end date.
//ToDo:
}

采纳答案by Matt Howells

static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end)
{
    for(var day = start.Date; day <= end; day = day.AddDays(1))
        yield return day;
}

Edit: Added code to solve your particular example and to demonstrate usage:

编辑:添加了代码来解决您的特定示例并演示用法:

var calculatedDates = 
    new List<string>
    (
        AllDatesBetween
        (
            DateTime.Parse("2009-07-27"),
            DateTime.Parse("2009-07-29")
        ).Select(d => d.ToString("yyyy-MM-dd"))
    );

回答by Simon P Stevens

The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this:

最简单的方法是取开始日期,并在其中添加 1 天(使用 AddDays),直到您到达结束日期。像这样的东西:

DateTime calcDate = start.Date;
while (calcDate <= end)
{
    calcDate = calcDate.AddDays(1);
    calculatedDates.Add(calcDate.ToString());
}

Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not.

显然,您可以根据是否要在集合中包含开始日期和结束日期来调整 while 条件和 AddDays 调用的位置。

[Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely]

[编辑:顺便说一句,您应该考虑使用 TryParse() 而不是 Parse(),以防传入的字符串不能很好地转换为日期]

回答by Timbo

for( DateTime i = start; i <= end; i = i.AddDays( 1 ) )
{
    Console.WriteLine(i.ToShortDateString());
}

回答by Binary Worrier

You just need to iterate from start to end, you can do this in a for loop

你只需要从头到尾迭代,你可以在 for 循环中做到这一点

DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

for(DateTime counter = start; counter <= end; counter = counter.AddDays(1))
{
    calculatedDates.Add(counter);
}

回答by Anant Dabhi

An alternative method

另一种方法

public static class MyExtensions
{
    public static IEnumerable EachDay(this DateTime start, DateTime end)
    {
        // Remove time info from start date (we only care about day). 
        DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
        while (currentDay <= end)
        {
            yield return currentDay;
            currentDay = currentDay.AddDays(1);
        }
    }
}

Now in the calling code you can do the following:

现在在调用代码中,您可以执行以下操作:

DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
    ...
}

Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.

这种方法的另一个优点是添加 EachWeek、EachMonth 等变得微不足道。然后这些都可以在 DateTime 上访问。