且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在两个日期之间循环

更新时间:2023-01-29 20:09:00

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

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

  var calculatedDates = 
new List< string>

AllDatesBetween

DateTime.Parse(2009-07-27),
DateTime.Parse(2009-07-29)
)。选择(d => d.ToString(yyyy-MM-dd))
);


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.

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:
}

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