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

时间:2012-03-28 17:11:25

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

我有两个日期时间范围:

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

我希望在此期间之间获得所有期间GROUPED BYYEAR。意思是输出必须是:

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来做这件事吗?

哦,夏令时不是绝对关键,但肯定是奖金。

谢谢!

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

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

答案 2 :(得分:1)

怎么样:

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

答案 3 :(得分:0)

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

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