How do you iterate through every day of the year?

后端 未结 8 554
春和景丽
春和景丽 2020-12-05 09:23

Given a start date of 1/1/2009 and an end date of 12/31/2009, how can I iterate through each date and retrieve a DateTime value using c#?

Thanks!

8条回答
  •  时光说笑
    2020-12-05 10:06

    An alternative method that might be more reusable is to write an extension method on DateTime and return an IEnumerable.

    For example, you can define a class:

    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.

提交回复
热议问题