Period And Duration Split Time Spans

Period.between splits a date span into calendar years, months, and days while ChronoUnit.DAYS gives the total; month-end overflow clamps instead of throwing.

JavaData Integrity

Code

snippet
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class TimeSpans {

    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 1, 31);
        LocalDate end = LocalDate.of(2026, 3, 15);

        // Period.between splits the span into calendar fields: years/months/days
        Period calendar = Period.between(start, end);
        System.out.println("months=" + calendar.getMonths() + " days=" + calendar.getDays());

        // ChronoUnit.DAYS reports only the total day count
        System.out.println("total days=" + ChronoUnit.DAYS.between(start, end));

        // adding one month: Jan 31 overflows and clamps to the last day of February
        System.out.println("one month later=" + start.plusMonths(1));

        // Duration measures precise elapsed time, with no calendar notion
        Duration span = Duration.between(
                Instant.parse("2026-11-21T00:00:00Z"),
                Instant.parse("2026-11-21T01:30:45Z"));
        System.out.println("seconds=" + span.getSeconds());
        System.out.println("minutes=" + span.toMinutes());

        // a reversed span can be made positive with abs
        Duration reversed = Duration.between(
                Instant.parse("2026-11-21T01:30:45Z"),
                Instant.parse("2026-11-21T00:00:00Z"));
        System.out.println("abs minutes=" + reversed.abs().toMinutes());
    }
}

What the demo measures

From Jan 31 to Mar 15, Period.between produces 1 month and 15 days, a calendar-field split rather than a day count. ChronoUnit.DAYS.between answers the other question, printing the total 43 days between the same two dates.

Month arithmetic clamps: start.plusMonths(1) turns Jan 31 into Feb 28 instead of throwing. Duration works on Instants without any calendar notion, so the 1h30m45s span prints 5445 seconds and 90 minutes, and the reversed span recovers via abs, printing 90 again.

Caveats and details

  • 2026 is not a leap year, so the clamp lands on Feb 28.
  • Duration.getSeconds predates toSeconds but equals it here.

Interactive Tools for This Topic

FAQ

Why does plusMonths not throw on Jan 31?
java.time clamps an overflowing day-of-month to the last valid day of the resulting month, so Jan 31 plus one month is Feb 28 in 2026; the demo prints it directly.