簡體   English   中英

獲取當前日歷月和接下來的11個月的日期

[英]Get dates from the current calendar month and the next 11 coming months

我有一個IEnumerable<DateTime> 我想提取當前日歷月中發生的所有日期,即使它們已經過去以及接下來的11個日歷月中的所有日期。 我將顯示從最近開始按月分組的日期。 例如:

當前日期 - 2012年3月12日

  • 2012年3月
    • 3月3日 - 活動1
    • 3月15日 - 活動2
    • 3月30日 - 活動3
  • ...
  • ...
  • ...
  • 2013年2月
    • 2月3日 - 事件156
    • 2月13日 - 事件157
    • 2月20日 - 活動158

我已經知道如何進行分組。 您將如何使用linq和C#完成過濾日期?

這樣的事情應該有效。 首先確定合法的日期范圍,然后篩選出該范圍之外的任何日期,最后按月分組。

我手工編寫了以下代碼,您可能需要調整它:

var acceptableFirstDate = DateTime.Today;
if (DateTime.Today.Day > 1)
{
    acceptableFirstDate = DateTime.Today.AddDays(-DateTime.Today.Day + 1);
}
var acceptableLastDate = acceptableFirstDate.AddMonths(12).AddDays(-1);

var result = dates
    .Where(x => x >= acceptableFirstDate && x <= acceptableLastDate)
    .GroupBy(x => x.Month);

我希望這有幫助!

暫無
暫無

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

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