79. Splitting a date-time range into equal intervals
Let’s consider a date-time range (bounded by a start date and an end date represented by two LocalDateTime
instances) and an integer n
. In order to split the given range into n
equal intervals, we start by defining a java.time.Duration
as follows:
Duration range = Duration.between(start, end);
Having this date-time range, we can rely on dividedBy()
to obtain a copy of it divided by the specified n
:
Duration interval = range.dividedBy(n - 1);
Finally, we can begin from the start date (the left head of the range) and repeatedly increment it with the interval
value until we reach the end date (the right head of the range). After each step, we store the new date in a list that will be returned at the end. Here is the complete code:
public static List<LocalDateTime> splitInEqualIntervals(
LocalDateTime start, LocalDateTime end, int n) {
Duration range = Duration.between(start, end);
Duration...