Duration vs Period: Temporal Amounts in java.time
What You'll Learn
You'll understand when to use Duration for time-based amounts and Period for date-based amounts, and why the distinction matters.
Time-Based vs Date-Based Amounts
Java's java.time API provides two different classes for representing amounts of time, and choosing the right one depends on what you're measuring:
Durationrepresents time-based amounts: hours, minutes, seconds, and nanosecondsPeriodrepresents date-based amounts: years, months, and days
Think of it this way: Duration measures time on a clock (like timing a race), while Period measures time on a calendar (like tracking someone's age).
Why Two Classes?
The separation exists because days are not always 24 hours due to daylight saving time transitions, and months vary in length. A Period of "1 month" doesn't have a fixed duration — it could be 28, 29, 30, or 31 days depending on the month.
Duration examples:
- "This meeting lasted 2 hours and 30 minutes"
- "The server responded in 150 milliseconds"
- "Add 5 hours to this timestamp"
Period examples:
- "I'm 25 years old"
- "The project deadline is 3 months away"
- "Add 10 days to this date"
Practical Guidance
Use Duration when working with:
Instant,LocalTime, orLocalDateTime(when time matters)- Precise measurements independent of calendars
Use Period when working with:
LocalDate(dates without time)- Human-readable calendar concepts
Key Takeaway: Duration measures precise time (hours/minutes/seconds), while Period measures calendar-based amounts (years/months/days). Choose based on whether you're measuring clock time or calendar time.