You can calculate date differences in Java using the ChronoUnit enum from the java.time package. The ChronoUnit class is used to measure the amount of time between two temporal objects (e.g., LocalDate, LocalDateTime, etc.) in terms of specific time units like DAYS, MONTHS, YEARS, etc.
Here’s an example of how to calculate the difference between two LocalDate objects in various time units:
Example Code
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateDifferenceExample {
public static void main(String[] args) {
// Define two dates
LocalDate date1 = LocalDate.of(2023, 1, 1);
LocalDate date2 = LocalDate.of(2025, 8, 7);
// Calculate differences using ChronoUnit
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
long monthsBetween = ChronoUnit.MONTHS.between(date1, date2);
long yearsBetween = ChronoUnit.YEARS.between(date1, date2);
// Print results
System.out.println("Days between: " + daysBetween);
System.out.println("Months between: " + monthsBetween);
System.out.println("Years between: " + yearsBetween);
}
}
Output
Days between: 949
Months between: 31
Years between: 2
Explanation
between()Method:- The
ChronoUnit.between()method takes two temporal objects as parameters and returns the difference in the specified unit (e.g., days, months, or years). - Ensure that the objects provided are compatible (e.g., both are
LocalDateorLocalDateTime).
- The
- Units of Measurement:
- The
ChronoUnitenum provides different constants such asDAYS,HOURS,WEEKS,MONTHS,YEARS, etc., to calculate differences at the desired granularity.
- The
- Signed Differences:
- The result may be negative if the first date is later than the second date. You can swap the dates if you want an absolute difference.
Other Temporal Types
ChronoUnit also works with other temporal types such as LocalDateTime, ZonedDateTime, Instant, etc. For example:
package org.kodejava.datetime;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeDifference {
public static void main(String[] args) {
LocalDateTime dateTime1 = LocalDateTime.of(2023, 1, 1, 10, 0);
LocalDateTime dateTime2 = LocalDateTime.of(2025, 8, 7, 12, 30);
long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
long minutesBetween = ChronoUnit.MINUTES.between(dateTime1, dateTime2);
System.out.println("Hours between: " + hoursBetween);
System.out.println("Minutes between: " + minutesBetween);
}
}
This will give you the time differences in hours and minutes.
Note
ChronoUnit.WEEKSmay not align perfectly withChronoUnit.DAYSdue to week boundaries.- Always validate whether the specific
ChronoUnitapplies to the temporal objects you’re comparing (e.g., you can’t useHOURSonLocalDatebecause it lacks time information).
