Java

java.time — Duration and Period

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Duration` for elapsed time (hours/minutes/seconds). `Period` for calendar amounts (days/months/years). Don't mix — calendar math respects month lengths and DST; clock math doesn't.
Java
Raw
import java.time.*;
import java.time.temporal.ChronoUnit;

class Demo {
    void example() {
        // Duration — based on seconds
        Duration d = Duration.ofMinutes(5);
        System.out.println(d.toMillis());         // 300000
        System.out.println(d.plusSeconds(30));    // PT5M30S

        // Difference between two Instants
        Instant start = Instant.now();
        // ... work ...
        Instant end = Instant.now();
        Duration elapsed = Duration.between(start, end);
        System.out.println(elapsed.toMillis() + " ms");

        // Period — calendar units
        Period p = Period.ofYears(1).plusMonths(2).plusDays(3);
        LocalDate then = LocalDate.now().plus(p);

        // Difference between dates
        LocalDate birth = LocalDate.of(1990, 5, 15);
        LocalDate now   = LocalDate.now();
        Period age = Period.between(birth, now);
        System.out.printf("%d years, %d months%n", age.getYears(), age.getMonths());

        // Total days between (use ChronoUnit, not Period for this)
        long totalDays = ChronoUnit.DAYS.between(birth, now);
        System.out.println(totalDays + " days");
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.