简体   繁体   English

获取当前日历月和接下来的11个月的日期

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

I have an IEnumerable<DateTime> . 我有一个IEnumerable<DateTime> I would like to pull out all dates that occur in the current calendar month even if they have passed as well as all dates in the next 11 calendar months. 我想提取当前日历月中发生的所有日期,即使它们已经过去以及接下来的11个日历月中的所有日期。 I'll be displaying the dates grouped by month starting with the most recent. 我将显示从最近开始按月分组的日期。 For example: 例如:

Current Date - Mar 12 2012 当前日期 - 2012年3月12日

  • March 2012 2012年3月
    • March 3 - Event 1 3月3日 - 活动1
    • March 15 - Event 2 3月15日 - 活动2
    • March 30 - Event 3 3月30日 - 活动3
  • ... ...
  • ... ...
  • ... ...
  • February 2013 2013年2月
    • Feb 3 - Event 156 2月3日 - 事件156
    • Feb 13 - Event 157 2月13日 - 事件157
    • Feb 20 - Event 158 2月20日 - 活动158

I already know how to do the grouping part. 我已经知道如何进行分组。 How would you accomplish filtering the dates using linq and C#? 您将如何使用linq和C#完成过滤日期?

Something like this should work. 这样的事情应该有效。 You first determine the legal range of dates, then filter out any dates that are outside of that range, and finally you group them by month. 首先确定合法的日期范围,然后筛选出该范围之外的任何日期,最后按月分组。

I wrote the following code by hand, you may need to tweak it: 我手工编写了以下代码,您可能需要调整它:

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

I hope this helps! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM