【问题标题】:Getting all DateTimes between two 'DateTime's in C#在 C# 中获取两个“日期时间”之间的所有日期时间
【发布时间】:2010-07-12 11:11:56
【问题描述】:

我有两个DateTimes,我想在这些日期之间获取所有DateTimes。例如,如果我的日期是 01.01.2010 - 05.01.2010,我的函数应该返回一个日期列表 (List),并且它必须包含 01.01.2010、02.01.2010、03.01.2010、04.01.2010 和05.01.2010.

我写了一个这样的函数。如果我的日期在一个月内,它工作正常。如果我的日期是 01.01.2010 - 05.02.2010,它就行不通了。因为月份变了,我的函数处理不了。 C# 中是否有一个函数可以返回两个日期之间的所有日期?或者我该如何处理月份变化?

public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
    {
        List<DateTime> allDates = new List<DateTime>();

        int starting = startingDate.Day;
        int ending = endingDate.Day;

        for (int i = starting; i <= ending; i++)
        {
            allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i));
        }

问题已解决,请参阅 Tim Robinson 的简单回答。

【问题讨论】:

    标签: c# datetime


    【解决方案1】:

    您可以直接在循环中使用DateTime 对象来代替您的intDateTime.AddDays 正确处理月末。

    for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
        allDates.Add(date);
    

    【讨论】:

      【解决方案2】:

      这样的事情怎么样?

      public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
      {
          return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
                           .Select(d => fromDate.AddDays(d));
      }
      

      编辑:现已测试。 :)

      【讨论】:

      • 正是我所需要的。工作,真的很干净。
      • 太棒了!这就是我需要的一行。
      【解决方案3】:
      public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
      {
          if (endingDate < startingDate)
          {
              throw new ArgumentException("endingDate should be after startingDate");
          }
          var ts = endingDate - startingDate;
          for (int i = 0; i < ts.TotalDays; i++)
          {
              yield return startingDate.AddDays(i);
          }
      }
      

      【讨论】:

      • yield 的使用很好,应该想到这一点。
      【解决方案4】:

      你是如此接近......只是不要使用日期,使用整个日期。

      static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
      {
          List<DateTime> allDates = new List<DateTime>();
      
      
          for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
          {
              allDates.Add(i);
          }
          return allDates.AsReadOnly();
      }
      

      【讨论】:

        【解决方案5】:

        给定字符串中较低的日期值和较高的日期值以及频率作为第三个参数,此方法应返回日期字典;其中键是日期范围的起始值,值是相应的范围。 如果频率是每周或每月,这很好用 - 您可以根据需要对其进行自定义。 传递的日期值应该是正确的格式,或者您可能需要使用 tryParseExact 或类似的东西对其进行格式化。

            protected static Dictionary<DateTime, String> getDateRange(String lowerDate, String higherDate, String frequency)
            {
                DateTime startDate, endDate;
                startDate = Convert.ToDateTime(lowerDate);
                endDate = Convert.ToDateTime(higherDate);
        
                Dictionary<DateTime, String> returnDict = new Dictionary<DateTime, String>();
        
                while (frequency.Equals("weekly") ? (startDate.AddDays(7) <= endDate) : (startDate.AddMonths(1) <= endDate))
                {
                    if (frequency.Equals("weekly"))
                    {
                        returnDict.Add(startDate, startDate + "-" + startDate.AddDays(7));
                        startDate = startDate.AddDays(8);
                    }
                    if (frequency.Equals("monthly"))
                    {
                        returnDict.Add(startDate, startDate + "-" + startDate.AddMonths(1));
                        startDate = startDate.AddMonths(1).AddDays(1);
                    }
                }
        
                returnDict.Add(startDate, startDate + "-" + endDate);
        
                return returnDict;
            }
        

        【讨论】:

        • 请格式化代码,使函数的第一行也格式化为代码。这个答案并没有解决问题,因为他写道他已经有两个 DateTimes 并且想要一个 List,但是您的函数使用字符串而不是 DateTimes 并返回一个 Dictionary 而不是一个列表。此外,他希望开始日期和结束日期之间的每个日期,而不仅仅是每周一次或每月一次。
        【解决方案6】:

        如果日期包含不同的时间,则最佳解决方案将失败。这是一个全天候的解决方案:

        全天:

        static public List<string> get_days_between_two_dates(DateTime start_date, DateTime end_date)
            {
                List<string> days_list = new List<string>();
                DateTime temp_start;
                DateTime temp_end;
        
                //--Normalize dates by getting rid of minues since they will get in the way when doing the loop
                temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day);
                temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day);
        
                //--Example Should return
                //--1-12-2014 5:59AM - 1-13-2014 6:01AM return 12 and 13
                for (DateTime date = temp_start; date <= temp_end; date = date.AddDays(1))
                {
                    days_list.Add(date.ToShortDateString());
                }
        
                return days_list;
            }
        

        所有时间:

        static public List<string> get_hours_between_two_dates(DateTime start_date, DateTime end_date)
            {
                List<string> hours_24_list = new List<string>();
                DateTime temp_start;
                DateTime temp_end;
        
                //--Normalize dates by getting rid of minutes since they will get in the way when doing the loop
                temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day, start_date.Hour, 0, 0);
                temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day, end_date.Hour, 0, 0);
        
                //--Example Should return
                //--5:59AM - 6:01AM return 5am and 6am
                for (DateTime date = temp_start; date <= temp_end; date = date.AddHours(1))
                {
                    hours_24_list.Add(date.ToShortTimeString());
                }
        
                return hours_24_list;
            }
        

        【讨论】:

          【解决方案7】:

          根据您的起始代码并使用撰写本文时可用的功能,这里有一个快速控制台应用程序来演示如何操作 - 请改用 AddDays()

          class Program
          {
              static void Main(string[] args)
              {
                  GetDates(new DateTime(2010, 1, 1), new DateTime(2010, 2, 5));
          
                  Console.ReadKey();
              }
          
              static List<DateTime> GetDates(DateTime startDate, DateTime endDate)
              {
                  List<DateTime> dates = new List<DateTime>();
          
                  while ((startDate = startDate.AddDays(1)) < endDate)
                      dates.Add(startDate);
          
                  return dates;
              }
          }
          

          虽然我认为Enumerable.Range() answer from Matt 是一个更好的解决方案。

          【讨论】:

            【解决方案8】:
            static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
            {
                List<DateTime> allDates = new List<DateTime>();
            
            
                for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
                {
                    allDates.Add(i);
                }
                return allDates.AsReadOnly();
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-08-09
              • 1970-01-01
              • 2019-06-22
              • 2012-03-24
              • 1970-01-01
              • 2013-09-08
              • 1970-01-01
              • 2012-05-09
              相关资源
              最近更新 更多