How to loop between two dates

后端 未结 5 1352
面向向阳花
面向向阳花 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条回答
  •  借酒劲吻你
    2021-02-04 02:29

    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.

提交回复
热议问题