Split date range into date range chunks

前端 未结 6 1312
温柔的废话
温柔的废话 2020-12-06 05:05

I am looking for a method of splitting a date range into a series of date ranges by chunk size of days. I am planning on using this to buffer calls to a service which if th

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 05:11

    There are a couple of problems with your solution:

    • the test newEnd == end may never be true, so the while could loop forever (I now see that this condition should always be triggered, but it wasn't obvious on first reading of the code; the while(true) feels a bit dangerous still)
    • AddDays is called three times for each iteration (minor performance issue)

    Here is an alternative:

    public IEnumerable> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
    {
        DateTime startOfThisPeriod = start;
        while (startOfThisPeriod < end)
        {
            DateTime endOfThisPeriod = startOfThisPeriod.AddDays(dayChunkSize);
            endOfThisPeriod = endOfThisPeriod < end ? endOfThisPeriod : end;
            yield return Tuple.Create(startOfThisPeriod, endOfThisPeriod);
            startOfThisPeriod = endOfThisPeriod;
        }
    }
    

    Note that this truncates the last period to end on end as given in the code in the question. If that's not needed, the second line of the while could be omitted, simplifying the method. Also, startOfThisPeriod isn't strictly necessary, but I felt that was clearer than reusing start.

提交回复
热议问题