Home > Software design >  Problem with splitting date range in a specific way
Problem with splitting date range in a specific way

Time:05-06

Let's say I have two DateTime objects like so and I want to split the date range into chunk size of days;

var date1 = new DateTime(2022, 3, 1, 8, 30, 0);
var date2 = new DateTime(2022, 3, 5, 11, 30, 0);

This method kind of does the job;

public static IEnumerable<Tuple<DateTime, DateTime>> 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);
}

And gives me a result set like so;

{(1.03.2022 08:30:00, 2.03.2022 08:30:00)}
{(2.03.2022 08:30:00, 3.03.2022 08:30:00)}
{(3.03.2022 08:30:00, 4.03.2022 08:30:00)}
{(4.03.2022 08:30:00, 5.03.2022 08:30:00)}
{(5.03.2022 08:30:00, 5.03.2022 11:30:00)}

What I actually need is a result set like so;

{(1.03.2022 08:30:00, 2.03.2022 00:00:00)}
{(2.03.2022 00:00:00, 3.03.2022 00:00:00)}
{(3.03.2022 00:00:00, 4.03.2022 00:00:00)}
{(4.03.2022 00:00:00, 5.03.2022 00:00:00)}
{(5.03.2022 00:00:00, 5.03.2022 11:30:00)}

Any ideas on how to do it?

CodePudding user response:

You could use the DateTime.Date property to truncate the time part.

Replace the following two lines:

yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;

With:

yield return Tuple.Create(start, chunkEnd.Date);
start = chunkEnd.Date;

CodePudding user response:

you could replace the timepart of the chuckend if it's not the first or last item in the collection with:

chunkEnd = new DateTime(chunkEnd.Year, chunkEnd.Month, chunkEnd.Day, 00, 00, 00);
  • Related