Back to Blog
Java

Java Duration vs Period: When to Use Each

java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.

java.timeDurationPerioddate-time APITemporalAmount
Comparison of Java Duration and Period for time and date calculations

java duration vs period requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When working with the Java date and time API, one common decision is choosing between java.time.Duration and java.time.Period. Both represent an amount of time, but they measure different units. Duration handles time-based units like hours, minutes, seconds, and nanoseconds, while Period handles date-based units like years, months, and days. Using the wrong one leads to subtle bugs, especially when crossing daylight saving time boundaries or dealing with calendar months.

Understanding Duration and Period

Duration and Period both implement TemporalAmount, but they are not interchangeable. Duration is a fixed length of time measured in seconds and nanoseconds. It does not account for calendar variations. Period is a date-based amount measured in years, months, and days, and it respects calendar semantics.

For example, adding Duration.ofDays(1) to a LocalDateTime always adds exactly 24 hours. Adding Period.ofDays(1) adds one calendar day, which may be 23 or 25 hours on a daylight saving change.

Key Differences: Time-Based vs Date-Based

The table below summarizes the primary differences:

AspectDurationPeriod
UnitsSeconds, nanosecondsYears, months, days
Target typesLocalTime, LocalDateTime, Instant, ZonedDateTimeLocalDate, LocalDateTime, ZonedDateTime
Calendar awareNoYes
Use caseMeasuring elapsed time, timeouts, intervalsAdding or subtracting calendar dates, scheduling

Duration is ideal for measuring elapsed time or specifying a timeout. Period is suitable for operations like "add one month to this date" or "calculate age in years."

Working with Duration

Duration is created from units like hours, minutes, seconds, or nanoseconds. You can also parse a string in ISO-8601 format, such as PT1H30M.

Duration timeout = Duration.ofMinutes(30); Duration interval = Duration.parse("PT1H30M");

Duration supports arithmetic operations like plus, minus, multipliedBy, and dividedBy. It also provides methods to convert to other units, such as toHours(), toMinutes(), and toNanos().

A common pattern is to use Duration with Instant to measure elapsed time:

Instant start = Instant.now(); // ... perform work Instant end = Instant.now(); Duration elapsed = Duration.between(start, end); System.out.println("Elapsed: " + elapsed.toMillis() + " ms");

Note that Duration.between works with Instant, LocalTime, and LocalDateTime, but not with LocalDate because a date alone does not have a time component.

Working with Period

Period is created from years, months, and days. It is commonly used with LocalDate to add or subtract calendar periods.

Period oneMonth = Period.ofMonths(1); LocalDate nextMonth = LocalDate.now().plus(oneMonth);

Period handles month-end correctly. For example, adding one month to January 31 yields February 28 (or 29 in a leap year), not March 3.

Period also supports between to calculate the difference between two dates in years, months, and days:

LocalDate start = LocalDate.of(2020, 1, 1); LocalDate end = LocalDate.of(2024, 6, 15); Period difference = Period.between(start, end); System.out.println(difference.getYears() + " years, " + difference.getMonths() + " months, " + difference.getDays() + " days");

Converting Between Duration and Period

Conversion is not straightforward because the units are not equivalent. You can convert a Duration to a Period by dividing into days, but this loses calendar awareness. Conversely, you can convert a Period to a Duration only if you know the start point, because the length of a month or year varies.

For example, to convert a Period to a Duration for a specific date:

LocalDate date = LocalDate.of(2024, 1, 1); Period period = Period.ofMonths(1); Duration duration = Duration.ofDays(period.getDays() + period.getMonths() * 30); // approximate

This approximation is not accurate for all months. A better approach is to use Temporal arithmetic:

LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); LocalDateTime end = start.plus(period); Duration duration = Duration.between(start, end);

This gives the exact duration for the given start point.

Common Pitfalls and Edge Cases

One common mistake is using Duration to add days to a LocalDate. Since Duration is time-based, adding Duration.ofDays(1) to a LocalDate throws an exception because LocalDate does not support time units. Instead, use Period.ofDays(1).

Another pitfall is assuming Period.between returns the total number of days. It returns the difference broken into years, months, and days. For example, between January 1 and February 1, it returns 1 month, not 31 days.

When working with ZonedDateTime, Duration respects the time line, but Period may cause unexpected results across daylight saving boundaries. Adding Period.ofDays(1) to a ZonedDateTime at 2 AM on a spring-forward day may shift the local time to 3 AM.

Choosing Between Duration and Period

Use Duration when you need a fixed amount of time that is independent of calendar rules. This includes timeouts, retry intervals, and measuring elapsed time. Use Period when you need to work with calendar dates, such as adding months to a due date, calculating age, or handling recurring monthly events.

If you are unsure, ask whether the amount is meant to represent a physical time span (use Duration) or a calendar-based span (use Period). For example, "add one month" is calendar-based, while "wait 30 seconds" is time-based.

Performance and Maintainability Considerations

Duration and Period are immutable and thread-safe, so they can be shared across threads without synchronization. They are lightweight objects, and the performance difference between them is typically not a deciding factor for most applications. The bigger concern is correctness: using the wrong type can lead to off-by-one errors or daylight saving issues.

From a maintainability perspective, choosing the correct type makes the code self-documenting. A Period of 1 month clearly expresses calendar intent, while a Duration of PT24H expresses a fixed time span. When the type matches the domain, future maintainers are less likely to introduce bugs.

java duration vs period: Practical Usage and Code Examples | RYUSLOG DEV