Split date range into date range chunks

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

    If you know how many chunks/intervals/periods/parts you want to split your time range into, I've found the following to be helpful

    You can use the DateTime.Ticks property to define your intervals, and then create a series of DateTime objects based on your defined interval:

    IEnumerable DivideTimeRangeIntoIntervals(DateTime startTS, DateTime endTS, int numberOfIntervals)
    {
        long startTSInTicks = startTS.Ticks;
        long endTsInTicks = endTS.Ticks;
        long tickSpan = endTS.Ticks - startTS.Ticks;
        long tickInterval = tickSpan / numberOfIntervals;
    
        List listOfDates = new List();
        for (long i = startTSInTicks; i <= endTsInTicks; i += tickInterval)
        {
            listOfDates.Add(new DateTime(i));
        }
        return listOfDates;
    }
    

    You can convert that listOfDates into however you want to represent a timerange (a tuple, a dedicated date range object, etc). You can also modify this function to directly return it in the form you need it.

提交回复
热议问题