如何将一段时间划分为年度?(将时间跨度划分为年度)

本文关键字:划分 时间跨度 一段时间 | 更新日期: 2023-09-27 18:29:22

我有两个日期时间范围:

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();
    static IList<Tuple<DateTime, DateTime>> GetDateRangesByYear(DateTime start, DateTime end)
    {
        List<Tuple<DateTime, DateTime>> ranges = new List<Tuple<DateTime,DateTime>>();
        for (int year = start.Year; year <= end.Year; ++year)
        {
            DateTime yearBegin = year == start.Year ? start : new DateTime(year, 1, 1);
            DateTime yearEnd = year == end.Year ? end : new DateTime(year, 12, 31);
            ranges.Add(Tuple.Create(yearBegin, yearEnd));
        }
        return ranges;
    }

关于:

static public List<Tuple<DateTime, DateTime>> GroupByYear(DateTime start, DateTime end)
{
    List<Tuple<DateTime, DateTime>> datetimes = Enumerable.Range(start.Year + 1, end.Year - 1 - start.Year)
                                                          .Select(x => new Tuple<DateTime, DateTime>(new DateTime(x, 1, 1), new DateTime(x, 12, 31)))
                                                          .ToList();
    datetimes.Add(new Tuple<DateTime, DateTime>(start, new DateTime(start.Year, 12, 31)));
    datetimes.Add(new Tuple<DateTime, DateTime>(new DateTime(end.Year, 1, 1), end));
    return datetimes.OrderBy(x => x.Item1.Year).ToList();
}

我没有检查所有的边缘情况,但这应该主要是

IList<Tuple<DateTime, DateTime>> GetYearPeriods(DateTime start, DateTime end)
{   
    var years = end.Year - start.Year - 1;
    var startDates = Enumerable.Range(start.Year+1, years)
                               .Select(year => new DateTime(year, 1, 1));
    var endDates = Enumerable.Range(start.Year+1, years)
                             .Select(year => new DateTime(year, 12, 31));
    var firstPeriod = Tuple.Create(start, new DateTime(start.Year, 12, 31));
    var middlePeriods = startDates.Zip(endDates, (s,e) => Tuple.Create(s, e));
    var lastPeriod = Tuple.Create(new DateTime(end.Year, 1, 1), end);
    return 
      (new[] {firstPeriod}).Union(middlePeriods).Union(new[] {lastPeriod}).ToList();
}