Duration and Period
Calculate time differences with type-safe Duration and Period.
Porównanie kodu
✕ 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);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Millisecond Math
Nowoczesne podejście
Duration / Period
Od JDK
8
Poziom trudności
Początkujący
Wsparcie JDK
Duration and Period
Dostępne
Widely available since JDK 8 (March 2014)
Jak to działa
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.
Powiązana dokumentacja