Split date range into date range chunks

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

    There are a lot of corner cases that are unhandled in the answers so far. And it's not entirely clear how you would want to handle them. Do you want overlapping start/end of ranges? Is there a minimum range size? Below is some code that'll handle some of the corner cases, you'll have to think about overlapping especially and possibly push the start/end of ranges by a few seconds or maybe more depending on the data you're returning.

        public static IEnumerable<(DateTime start, DateTime end)> PartitionDateRange(DateTime start,
                                                                                    DateTime end,
                                                                                    int chunkSizeInDays)
        {
            if (start > end)
                yield break;
    
            if (end - start < TimeSpan.FromDays(chunkSizeInDays))
            {
                yield return (start, end);
                yield break;
            }
    
            DateTime e = start.AddDays(chunkSizeInDays);
    
            for (;e < end; e = e.AddDays(chunkSizeInDays))
            {
                yield return (e.AddDays(-chunkSizeInDays), e);
            }
    
            if (e < end && end - e > TimeSpan.FromMinutes(1))
                yield return (e, end);
        }
    

    Example call:

        static void Main(string[] _)
        {
            Console.WriteLine("expected");
    
            DateTime start = DateTime.Now - TimeSpan.FromDays(10);
            DateTime end = DateTime.Now;
    
            foreach (var range in PartitionDateRange(start, end, 2))
            {
                Console.WriteLine($"{range.start} to {range.end}");
            }
    
            Console.WriteLine("start > end");
    
            start = end + TimeSpan.FromDays(1);
    
            foreach (var range in PartitionDateRange(start, end, 2))
            {
                Console.WriteLine($"{range.start} to {range.end}");
            }
    
            Console.WriteLine("less than partition size");
    
            start = end - TimeSpan.FromDays(1);
    
            foreach (var range in PartitionDateRange(start, end, 2))
            {
                Console.WriteLine($"{range.start} to {range.end}");
            }
        }
    

提交回复
热议问题