【问题标题】:Best Way To Get All Dates Between DateA and DateB获取 DateS 和 Date 之间所有日期的最佳方法
【发布时间】:2010-09-14 20:48:14
【问题描述】:

我正在使用 asp:Calander,并且我有一个具有开始日期和结束日期的对象。我需要获取这两个日期之间的所有日期并将它们放在一个数组中,这样我就可以使用不同的 CSS 在日历上呈现相应的日期

【问题讨论】:

    标签: asp.net css date


    【解决方案1】:
    IEnumerable<DateTime> RangeDays(DateTime RangeStart, DateTime RangeEnd) {
       DateTime EndDate = RangeEnd.Date;
    
       for (DateTime WorkDate = RangeStart.Date; WorkDate <= EndDate; WorkDate = WorkDate.AddDays(1)) {
          yield return WorkDate;
       }
    
       yield break;
    }
    

    未经测试的代码...但应该可以工作。

    【讨论】:

    • 我不了解 asp.net 日历,但考虑到结束日期总是大于开始日期,它可以很好地获取开始日期和日期之间的日期。
    【解决方案2】:
    // inclusive
    var allDates = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(i => startDate.AddDays(i));
    
    // exclusive
    var allDates = Enumerable.Range(1, (endDate - startDate).Days).Select(i => startDate.AddDays(i));
    

    【讨论】:

      【解决方案3】:

      我投票支持 AlbertEin 是因为他给出了一个很好的答案,但你真的需要一个收藏来保存所有日期吗?当您渲染一天时,您不能只检查日期是否在指定范围内,然后以不同的方式渲染它,不需要集合。这里有一些代码来演示

      DateTime RangeStartDate,RangeEndDate; //Init as necessary
      DateTime CalendarStartDate,CalendarEndDate; //Init as necessary
      DateTime CurrentDate = CalendarStartDate;
      
      String CSSClass;
      
      while (CurrentDate != CalendarEndDate)
      {
          if(CurrentDate >= RangeStartDate && CurrentDate <= RangeEndDate)
          {
              CSSClass= "InRange";
          }     
          else
          {
              CSSClass = "OutOfRange";
          }
          //Code For rendering calendar goes here
          currentDate = currentDate.AddDays (1);
      }
      

      【讨论】:

        【解决方案4】:
        DateTime startDate;
        DateTime endDate;
        
        DateTime currentDate = startDate;
        List<DateTime> dates = new List<DateTime> ();
        
        while (true)
        {
            dates.Add (currentDate);
            if (currentDate.Equals (endDate)) break;
            currentDate = currentDate.AddDays (1);
        }
        

        假设 startDate

        【讨论】:

        • 我知道在 VB.NET AddDays 返回一个需要分配的日期对象。它将像这样使用“currentDate = currentDate.AddDays(1)。我不确定在 C# 中是否相同。
        猜你喜欢
        • 2013-11-13
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        • 2013-08-09
        • 2015-06-18
        • 2019-05-31
        • 2011-06-05
        • 1970-01-01
        相关资源
        最近更新 更多