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

Ami*_*ail 31 c# datetime list

我想制作一个需要一个月和一年的功能,并在本月返回List<DateTime>所有日期.

任何帮助将不胜感激

提前致谢

Ani*_*Ani 78

这是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
}
Run Code Online (Sandbox Code Playgroud)

还有一个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;
}
Run Code Online (Sandbox Code Playgroud)

你可能想要考虑返回一个日期的流序列,而不是List<DateTime>让调用者决定是否将日期加载到列表或数组中/后处理它们/部分迭代它们等.对于LINQ版本,你可以通过删除来实现这一点打电话给ToList().对于for循环,您可能希望实现一个迭代器.在这两种情况下,返回类型都必须更改为IEnumerable<DateTime>.

  • 哦,我喜欢Linq版本.真好.非常有教育意义的Linq新手,谢谢. (2认同)

Ste*_*end 5

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

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);
Run Code Online (Sandbox Code Playgroud)