【问题标题】:How to get All Dates in a given month in C#如何在C#中获取给定月份的所有日期
【发布时间】:2010-10-03 13:40:45
【问题描述】:

我想创建一个函数,该函数需要月份和年份并返回 List<DateTime> 填充本月的所有日期。

任何帮助将不胜感激

提前致谢

【问题讨论】:

    标签: c# list datetime


    【解决方案1】:

    这是一个使用 LINQ 的解决方案:

    public static List<DateTime> GetDates(int year, int month)
    {
       return Enumerable.Range(1, DateTime.DaysInMonth(year, month))  // Days: 1, 2 ... 31 etc.
                        .Select(day => new DateTime(year, month, day)) // Map each day to a date
                        .ToList(); // Load dates into a list
    }
    

    还有一个带有for循环的:

    public static List<DateTime> GetDates(int year, int month)
    {
       var dates = new List<DateTime>();
    
       // Loop from the first day of the month until we hit the next month, moving forward a day at a time
       for (var date = new DateTime(year, month, 1); date.Month == month; date = date.AddDays(1))
       {
          dates.Add(date);       
       }
    
       return dates;
    }
    

    您可能需要考虑返回日期的流式序列而不是 List&lt;DateTime&gt;,让调用者决定是否将日期加载到列表或数组中/对它们进行后处理/部分迭代它们等。对于 LINQ 版本,您可以通过删除对ToList() 的调用来完成此操作。对于 for 循环,您需要实现 iterator。在这两种情况下,返回类型都必须更改为 IEnumerable&lt;DateTime&gt;

    【讨论】:

    • 哦,我喜欢 Linq 版本。那很好。对 Linq 新手很有教育意义,谢谢。
    • @Ani 很好的答案。有没有办法使用 Linq 语法来获取日期范围,比如从一个月的第一天到指定的日期? IE。日期从 6 月 1 日 -> 6 月 20 日。
    【解决方案2】:

    Linq 框架之前版本的示例,使用 1999 年 2 月。

    int year = 1999;
    int month = 2;
    
    List<DateTime> list = new List<DateTime>();
    DateTime date = new DateTime(year, month, 1);
    
    do
    {
      list.Add(date);
      date = date.AddDays(1);
    while (date.Month == month);
    

    【讨论】:

    • 我猜date.Month == 2 应该是date.Month == month :)
    • 伙计,这是我在您发布此内容 6 年后遇到的最佳答案。如此简单易读,谢谢。
    【解决方案3】:

    我相信可能有更好的方法来做到这一点。但是,你可以使用这个:

    public List<DateTime> getAllDates(int year, int month)
    {
        var ret = new List<DateTime>();
        for (int i=1; i<=DateTime.DaysInMonth(year,month); i++) {
            ret.Add(new DateTime(year, month, i));
        }
        return ret;
    }
    

    【讨论】:

      【解决方案4】:

      给你:

          public List<DateTime> AllDatesInAMonth(int month, int year)
          {
              var firstOftargetMonth = new DateTime(year, month, 1);
              var firstOfNextMonth = firstOftargetMonth.AddMonths(1);
      
              var allDates = new List<DateTime>();
      
              for (DateTime date = firstOftargetMonth; date < firstOfNextMonth; date = date.AddDays(1) )
              {
                  allDates.Add(date);
              }
      
              return allDates;
          }
      

      遍历从您想要的月份的第一天到最后一个小于下个月第一天的日期。

      PS:如果这是作业,请标记为“作业”!

      【讨论】:

        猜你喜欢
        • 2014-07-09
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-17
        • 1970-01-01
        相关资源
        最近更新 更多