How to loop between two dates

后端 未结 5 1351
面向向阳花
面向向阳花 2021-02-04 02:12

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

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 02:49

    static IEnumerable 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
        (
            AllDatesBetween
            (
                DateTime.Parse("2009-07-27"),
                DateTime.Parse("2009-07-29")
            ).Select(d => d.ToString("yyyy-MM-dd"))
        );
    

提交回复
热议问题