如何获得C中给定月份的所有日期#

问题描述:

我想创建一个采用月份和年份的函数,并返回填充本月中所有日期的List<DateTime>如何获得C中给定月份的所有日期#

任何帮助将不胜感激提前

下面是使用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<DateTime>,让调用者决定是否将日期加载到列表或数组中/后处理它们/部分迭代它们等。对于LINQ版本,您可以通过删除呼叫ToList()。对于for循环,您将需要实现一个iterator。在这两种情况下,返回类型都必须更改为IEnumerable<DateTime>

+2

哦,我喜欢Linq版本。这很好。非常受Linq新手的教育,谢谢。 – Lunivore 2010-10-03 13:53:31

+0

@Ani很棒的回答。有没有一种方法可以使用Linq语法来获取一系列日期,例如从一个月的第一天到指定的日期? 即。日期从6月1日 - > 6月20日。 – Josh 2012-02-23 11:00:09

感谢我相信有可能是更好的方式来做到这一点。但是,你可以这样做:

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

样品预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); 
+0

我猜'date.Month == 2'应该是'date.Month == month' :) – 2010-10-03 14:21:26

+0

@lasseespeholt - 谢谢,修正 – 2010-10-03 14:24:54

+0

男人,这是我遇到的最好的答案即使在6年后你发布了这个。如此简单如此可读,谢谢。 – Kadaj 2016-10-20 12:28:19

在这里你去:通过日期

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:如果这是作业,请用“作业”标记!