簡體   English   中英

如何在C#中獲得給定月份的所有日期

[英]How to get All Dates in a given month in C#

我想創建一個帶月和年的函數,並返回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循環,您可能希望實現一個迭代器 在這兩種情況下,返回類型都必須更改為IEnumerable<DateTime>

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);

我相信可能有更好的方法來做到這一點。 但是,你可以使用這個:

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:如果這是作業,請用“作業”標記!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM