How to split the time range by date in java

900 Views Asked by At

If I have a StartTime and EndTime (it might be milliseconds or java.time.Instant etc). I want to Split the range into different list day wise.

Ex : If input StartTime (01-Jan-2022 7.00)and EndTime(05-Jan-2022 10:00) Then the output should have List of

StartTime(01-Jan-2022 07.00) and EndTime(01-Jan-2022 23.59)
StartTime(02-Jan-2022 00.00) and EndTime(02-Jan-2022 23.59)
StartTime(03-Jan-2022 00.00) and EndTime(03-Jan-2022 23.59)
StartTime(04-Jan-2022 00.00) and EndTime(04-Jan-2022 23.59)
StartTime(05-Jan-2022 00.00) and EndTime(05-Jan-2022 10:00)

Ex : If input StartTime (01-Jan-2022 7.00)and EndTime(01-Jan-2022 10:00) Then the output should have List should have one one item

StartTime(01-Jan-2022 07.00) and EndTime(01-Jan-2022 10:00)

1

There are 1 best solutions below

0
JAMBUGOLA MAHESH On

One of the way is to use below logic

        while (startInstant.truncatedTo(ChronoUnit.DAYS).isBefore(endInstant.truncatedTo(ChronoUnit.DAYS))) {

        Instant startDayInstant = startInstant.truncatedTo(ChronoUnit.DAYS);
        Instant nextDayInstant = startDayInstant.plus(1, ChronoUnit.DAYS);
        timeRanges.add(new TimeRange(startDayInstant, startInstant, nextDayInstant.minusMillis(1)));
        startInstant = nextDayInstant;

    }
    timeRanges.add(new TimeRange(startInstant.truncatedTo(ChronoUnit.DAYS),
                    startInstant, endInstant));
    System.out.println(timeRanges);