Explain Codes LogoExplain Codes Logo

How to compare dates in Java?

java
date-comparison
java-8
time-zones
Alex KataevbyAlex Kataev·Feb 15, 2025
TLDR

Java's LocalDate offers isBefore, isAfter, and isEqual methods for comparing dates - and it's as simple as this:

LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plusDays(1); System.out.println(today.isBefore(tomorrow)); // true, unless you've discovered time travel System.out.println(today.isEqual(tomorrow)); // false, unless your code runs at 88mph System.out.println(today.isAfter(tomorrow)); // false, check again tomorrow maybe?

These methods quickly determine if today is before, equal to, or after tomorrow.

Including the dates in range

Often, you want to see if a date falls within a specific range, and the border dates should count:

LocalDate startDate = LocalDate.parse("2023-01-01"); LocalDate endDate = LocalDate.parse("2023-12-31"); // Is 'today' between 'startDate' (inclusive) and 'endDate' (inclusive)? boolean isWithinRange = !today.isBefore(startDate) && !today.isAfter(endDate); System.out.println(isWithinRange); // Output depends on today's shenanigans

This tells us if today is in the inclusive range of the start and end dates.

Time travel across time zones

Time zones can turn simple date comparisons into a world tour. Here's ZonedDateTime taking us from now to UTC:

ZonedDateTime zonedNow = ZonedDateTime.now(); ZonedDateTime zonedTomorrow = zonedNow.plusDays(1).withZoneSameInstant(ZoneId.of("UTC")); System.out.println(zonedNow.isBefore(zonedTomorrow)); // true (unless you live in UTC)

With this, you can compare dates accurately across different time zones.

Beware! Here be dragons (Edge cases)

Dates are sprinkled with interesting edge cases. Here's your sword and shield:

Leap years and daylight savings

When dealing with leap years or daylight savings, avoid the dragon's fire with ZonedDateTime.

Null dates - the invisible dragon

Demolish the invisible foe, NullPointerException, by always checking for null:

LocalDate otherDate = // ... if (otherDate != null && today.isAfter(otherDate)) { // The 'null' dragon is not here, safe to proceed. }

Legacy Date and Calendar - ancient dragons

If you're stuck with the ancient dragons Date or Calendar, here's your map:

Date date1 = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); calendar.add(Calendar.DATE, 1); Date date2 = calendar.getTime(); System.out.println(date2.after(date1)); // true (if your map is in the right orientation)

But try upgrading your gear to java.time if you can.

Database dates - the hidden dungeons

Working with database dates? Equip your java.time objects using JDBC 4.2 or later to limit conversions and overhead:

PreparedStatement pstmt = con.prepareStatement("SELECT * FROM mytable WHERE date_column = ?"); pstmt.setObject(1, LocalDate.now()); ResultSet rs = pstmt.executeQuery();

With this, you're using modern equipment in database dungeons.