代码之家  ›  专栏  ›  技术社区  ›  Alex

在StartDate和EndDate之间迭代每一天[重复]

  •  45
  • Alex  · 技术社区  · 15 年前

    我有一个 DateTime 开始日期和结束日期。

    我怎么能不考虑时间,每天在这两个时间段之间迭代呢?

    凌晨1:59:12。

    我希望能够遍历7/20,7/21,7/22。。7/29.

    5 回复  |  直到 11 年前
        1
  •  137
  •   Yuriy Faktorovich    15 年前
    for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
    {
        ...
    }
    

    .Date是确保你有最后一天,如示例中所示。

        2
  •  14
  •   healsjnr    13 年前

    另一种更易重用的方法是在DateTime上编写扩展方法并返回IEnumerable。

    例如,可以定义一个类:

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

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

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

    这种方法的另一个优点是,它使每个星期、每个月等的添加变得很简单,这些都可以在DateTime上访问。

        3
  •  3
  •   haraman    9 年前

    你得小心结束日期。例如,在

    示例:开始日期为2010年7月20日下午5:10:32,结束日期为2010年7月29日上午1:59:12。
    我希望能够遍历7/20,7/21,7/22。。7/29.

    date < endDate 永远不包括7/29。当你把一天的时间加到7/28下午5:10-它变成7/29下午5:10,比7/29凌晨2点高。

    如果那不是你想要的,那我就说你想要

    for (DateTime date = start.Date; date <= end.Date; date += TimeSpan.FromDays(1))
    {
         Console.WriteLine(date.ToString());
    }
    

    或者类似的东西。

        4
  •  3
  •   Henk Kok    9 年前

    @Yuriy Faktorovich,@healsjrn和@mho的循环都会抛出一个 System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime 例外如果 EndDate == DateTime.MaxValue . 为了防止这种情况,在循环的末尾添加一个额外的检查

    for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
    {
       ...
       if (date.Date == DateTime.MaxValue.Date)
       {
           break;
       }
    }
    

    (我本想把这个作为评论发到@Yuriy Faktorovich的答案上,但我缺乏声誉)

        5
  •  0
  •   benPearce    15 年前
    DateTime date = DateTime.Now;
    DateTime endDate = date.AddDays(10);
    
    while (date < endDate)
    {
      Console.WriteLine(date);
      date = date.AddDays(1);
    }
    
    推荐文章