Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

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...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard