Date/Time beginner

Duration and Period

Calculate time differences with type-safe Duration and Period.

✕ Pre-Java 8
// How many days between two dates?
long diff = date2.getTime()
    - date1.getTime();
long days = diff
    / (1000 * 60 * 60 * 24);
// ignores DST, leap seconds
✓ Java 8+
long days = ChronoUnit.DAYS
    .between(date1, date2);
Period period = Period.between(
    date1, date2);
Duration elapsed = Duration.between(
    time1, time2);
🎯

Type-safe

Duration for time, Period for dates — no confusion.

🛡️

Correct math

Handles DST transitions, leap years, and leap seconds.

📖

Readable

ChronoUnit.DAYS.between() reads like English.

Old Approach
Millisecond Math
Modern Approach
Duration / Period
Since JDK
8
Difficulty
beginner
Duration and Period
Available

Widely available since JDK 8 (March 2014)

How it works

Duration is for time-based amounts (hours, minutes, seconds). Period is for date-based amounts (years, months, days). ChronoUnit.between() for simple differences. All handle edge cases correctly.

Share 𝕏 🦋 in