如何获取所有日期在一个给定的月份在C# [英] How to get All Dates in a given month in C#
问题描述
我想制作一个月份和年份的函数,并返回列表< DateTime>
,填充本月所有日期。
I want to make a function that take month and year and return List<DateTime>
filled with all dates in this month.
任何帮助将不胜感激
感谢提前
推荐答案
这是LINQ的一个解决方案:
Here's a solution with 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
}
一个带循环:
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;
}
您可能需要考虑返回一串流日期而不是列表< DateTime>
,让调用者决定是否将日期加载到列表或数组/后处理它们/部分迭代它们。对于LINQ版本,您可以通过删除对 ToList()
的调用。对于for循环,您需要实现迭代器。在这两种情况下,返回类型都必须更改为 IEnumerable< DateTime>
。
You might want to consider returning a streaming sequence of dates instead of List<DateTime>
, letting the caller decide whether to load the dates into a list or array / post-process them / partially iterate them etc. For the LINQ version, you can accomplish this by removing the call to ToList()
. For the for-loop, you would want to implement an iterator. In both cases, the return-type would have to be changed to IEnumerable<DateTime>
.
这篇关于如何获取所有日期在一个给定的月份在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!