Period and Duration

Measuring Time Between Two Points

PeriodDurationChronoUnit.X.between
Measuresyears, months, dayshours, minutes, seconds, nanosa single unit total
Works withLocalDatetimes, date-times, instantsany temporal
Exampleage: 24 years 6 monthsride took 1h 25mloan is 45 days overdue

Age, Durations and Day Counts

Example

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        LocalDate dob = LocalDate.of(2000, 3, 14);
        LocalDate today = LocalDate.of(2024, 9, 1);
        Period age = Period.between(dob, today);
        System.out.println("Age: " + age.getYears() + " years, " + age.getMonths() + " months, " + age.getDays() + " days");
        System.out.println("Period as text: " + age);

        long days = ChronoUnit.DAYS.between(LocalDate.of(2024, 1, 1), today);
        System.out.println("Days since new year: " + days);

        Duration ride = Duration.between(LocalTime.of(8, 45), LocalTime.of(10, 10));
        System.out.println("Ride: " + ride.toHours() + "h " + ride.toMinutesPart() + "m (" + ride + ")");

        LocalDateTime start = LocalDateTime.of(2024, 9, 1, 22, 0);
        LocalDateTime end = start.plus(Duration.ofMinutes(150));
        System.out.println("Movie ends at " + end.toLocalTime() + " on " + end.toLocalDate());

        LocalDate trialEnd = today.plus(Period.ofMonths(1));
        System.out.println("Free trial ends " + trialEnd);
    }
}

Output

Age: 24 years, 5 months, 18 days
Period as text: P24Y5M18D
Days since new year: 244
Ride: 1h 25m (PT1H25M)
Movie ends at 00:30 on 2024-09-02
Free trial ends 2024-10-01