Split date range into date range chunks

前端 未结 6 1310
温柔的废话
温柔的废话 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:20

    I think your code fails when the difference between start and end is smaller than dayChunkSize. See this:

    var singleRange = SplitDateRange(DateTime.Now, DateTime.Now.AddDays(7), dayChunkSize: 15).ToList();
    Debug.Assert(singleRange.Count == 1);
    

    Proposed solution:

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

提交回复
热议问题