c# - 如何将一段时间分组为年度? (将时间跨度分成年度)

标签 c# .net linq datetime linq-to-objects

我有两个日期时间范围:

DateTime start = new DateTime(2012,4,1);
DateTime end = new DateTime(2016,7,1);

我希望在此期间之间按年份分组所有期间。这意味着输出必须是:

2012-04-01 - 2012-12-31
2013-01-01 - 2013-12-31
2014-01-01 - 2014-12-31
2015-01-01 - 2015-12-31
2016-01-01 - 2016-07-01

最好输出在 IList<Tuple<DateTime,DateTime>> 中列表。

你会怎么做?无论如何,有没有办法用 LINQ 做到这一点?

哦,夏令时并不是绝对重要,但肯定是一个奖励。

谢谢!

最佳答案

DateTime start = new DateTime(2012,4,1); 
DateTime end = new DateTime(2016,7,1); 

var dates = from year in Enumerable.Range(start.Year,end.Year-start.Year+1)
        let yearStart=new DateTime(year,1,1)
        let yearEnd=new DateTime(year,12,31)
        select Tuple.Create(start>yearStart ? start : yearStart, end<yearEnd ? end : yearEnd); 

IList<Tuple<DateTime,DateTime>> result = dates.ToList();

关于c# - 如何将一段时间分组为年度? (将时间跨度分成年度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9912449/

相关文章:

.net - 在我按照 OWAPS 和 Roslyn Security Guard 的建议应用解决方案后,Veracode 仍然报告操作系统命令注入(inject)问题

c# - Union 或 Concat 中的类型不能用层次结构构造

c# - 当每个项目都包含对其父项的引用时,从项目列表创建树

c# - 如何将 Safari 与 Selenium 2.0 一起使用?

c# - 如何向 Swagger 添加健康检查

c# - 单例类的几个实例

c# - 如何在 lambda 表达式或 linq 中执行此操作?

.net - .SaveChanges 不对 Entity Framework 中的数据库应用更改

c# - 数据类型和古怪的结果 PHP/C#/WinForms

c#迭代列表以合并具有相同字段的项目