Explain Codes LogoExplain Codes Logo

How to iterate through range of Dates in Java?

java
date-manipulation
java-8
functional-programming
Alex KataevbyAlex Kataev·Dec 2, 2024
TLDR

Effortlessly traverse a date range in Java with LocalDate as your time-travel device and plusDays as its fuel source:

LocalDate start = LocalDate.of(2023, 1, 1), end = LocalDate.of(2023, 1, 5); for (; !start.isAfter(end); start = start.plusDays(1)) { // Be Bill Murray, every day is a new one. Groundhog day! System.out.println(start); }

Key takeaway: run a loop from the start date to the end date, jumping one day at a time using plusDays.

Alternatives for jumping through time

Streams: the fancy way

Java 9 brought us datesUntil(): a neat function producing a Stream<LocalDate>, perfect for hopping between dates:

LocalDate start = LocalDate.of(2023, 1, 1); LocalDate end = LocalDate.of(2023, 1, 5); // Make it rain dates! start.datesUntil(end.plusDays(1)).forEach(System.out::println);

This gives us a functional-style way to traverse dates smoothly, without tripping over leap years or complex date calculations.

When "days" are more than just "dates"

For counting the exact number of days between two dates, ChronoUnit.DAYS.between is your friend:

long daysBetween = ChronoUnit.DAYS.between(start, end); // Wow, so many days...and yet, so few weekends.

Useful when you need to set an iteration based on day count.

Shoutout to classical music: the while loop

A more traditional while loop could be more readable for some:

// Tempus fugit, but you can keep track of it. while (!start.isAfter(end)) { System.out.println(start); start = start.plusDays(1); }

Perfect for those who appreciate a good classic.

Advanced Provider: Additional Scenarios and Spotlight on Pitfalls

Spin up the DeLorean for pre-Java 8

Pre-Java 8, the Joda Time library comes to our rescue:

DateTime start = new DateTime(2023, 1, 1, 0, 0); DateTime end = new DateTime(2023, 1, 5, 0, 0); // Step out of the DeLorean, Marty McFly! We're in a new date. while (start.isBefore(end)) { System.out.println(start); start = start.plusDays(1); }

Just be sure to add Joda Time to your project dependencies. Your future self will thank you.

Dates sometimes talk Strings

Sometimes, we start with string representations:

// Be a Pygmalion, transforming Strings into Dates. LocalDate start = LocalDate.parse("2023-01-01"); LocalDate end = LocalDate.parse("2023-01-05");

Remember that the date format should match Java's ISO-8601 standard, lest you get a DateTimeParseException—the "string cheese" of date manipulation!

Going Retro with Calendar

In truly classic Java (before Java 8 and without Joda), the good ol' Calendar does the job:

Calendar start = new GregorianCalendar(2023, Calendar.JANUARY, 1); Calendar end = new GregorianCalendar(2023, Calendar.JANUARY, 5); // It's a date marathon, not a sprint. while (start.before(end)) { System.out.println(start.getTime()); start.add(Calendar.DATE, 1); }

The least convenient of options, but sometimes you can't choose your tools!

When you're in between old and new date forms

If you're working with java.util.Date, converting it to LocalDate makes things easier:

Date oldDate = new Date(); LocalDate newDate = oldDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // And presto! Your old date just got a dose of millennial freshness!

This is a lifesaver while dealing with legacy code.