All 15 Java Date & Time API (java.time) questions
More in Java Date & Time API (java.time)
Advertisement
Back to results for “Date”
Java › Java Date & Time API (java.time)

How would you calculate the difference between two dates or times using Period and Duration, and what's the distinction between these two classes?

Intermediate

Answer

Period represents a date-based amount of time in human calendar terms (years, months, days), appropriate for calculating differences between LocalDate values where calendar irregularities matter (like a month having a variable number of days); Duration represents a time-based amount measured in exact seconds/nanoseconds, appropriate for calculating differences between time-based or instant-based values (LocalTime, Instant) where you want a precise, fixed-length elapsed time rather than a calendar-relative one -- using the wrong one for a given scenario (like computing a Duration between two LocalDate values) either won't compile or won't give calendar-meaningful results.
LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate end = LocalDate.of(2024, 6, 20);
Period period = Period.between(start, end);
System.out.println(period.getMonths() + " months, " + period.getDays() + " days");  // calendar-aware difference

Instant startTime = Instant.now();
Instant endTime = startTime.plusSeconds(3661);
Duration duration = Duration.between(startTime, endTime);
System.out.println(duration.toHours() + "h " + duration.toMinutesPart() + "m");  // exact elapsed time
Real-world example An age-calculation feature uses Period.between() to correctly compute a person's age in calendar-meaningful years and months (correctly accounting for varying month lengths and leap years), while a separate performance-monitoring feature uses Duration.between() on two Instant timestamps to measure precise elapsed processing time in milliseconds for a request.

Common follow-ups: What happens if you try to compute a Period between two Instant values, or a Duration between two LocalDate values -- does it compile?;How does Period.between() handle the calculation when the day-of-month values don't align evenly (like from January 31 to March 1)?