我想制作一个函数,获取月份和年份并返回
List<DateTime>
填充本月的所有日期。
任何帮助将不胜感激
提前致谢
这是 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>
。
Linq Framework 之前版本的示例,使用 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);
我确信可能有更好的方法来做到这一点。但是,你可以使用这个:
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;
}
给你:
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:如果这是作业,请标记为“作业”!
int 年 = 2024 年; 整数月份 = 3;
int daysInMonth = DateTime.DaysInMonth(年,月);