【发布时间】:2010-10-03 13:40:45
【问题描述】:
我想创建一个函数,该函数需要月份和年份并返回 List<DateTime> 填充本月的所有日期。
任何帮助将不胜感激
提前致谢
【问题讨论】:
我想创建一个函数,该函数需要月份和年份并返回 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 框架之前版本的示例,使用 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 :)
我相信可能有更好的方法来做到这一点。但是,你可以使用这个:
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:如果这是作业,请标记为“作业”!
【讨论】: