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

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

任何帮助将不胜感激

提前致谢

这是LINQ的解决方案:

 public static List 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 GetDates(int year, int month) { var dates = new List(); // 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 ,让调用者决定是将日期加载到列表还是数组/后处理它们/部分迭代它们等。对于LINQ版本,您可以通过删除对ToList()的调用来完成此操作。 对于for循环,您可能希望实现一个迭代器 。 在这两种情况下,返回类型都必须更改为IEnumerable

1999年2月使用前Linq Framework版本的示例。

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

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

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

干得好:

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

迭代从您想要的月份的第一个日期到最后一个日期,该日期小于下个月的第一个日期。

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