How to compare dates in Java?
Java's LocalDate
offers isBefore
, isAfter
, and isEqual
methods for comparing dates - and it's as simple as this:
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:
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:
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:
Legacy Date
and Calendar
- ancient dragons
If you're stuck with the ancient dragons Date
or Calendar
, here's your map:
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:
With this, you're using modern equipment in database dungeons.
Was this article helpful?