Period Measures Calendar Date Spans

Use java.time.Period for calendar-based spans across months and years, where adding two months means something different every time.

JavaData Integrity

Code

snippet
import java.time.LocalDate;
import java.time.Period;

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

        Period span = Period.between(start, end);
        System.out.println("span: " + span);
        System.out.println("years=" + span.getYears()
            + " months=" + span.getMonths()
            + " days=" + span.getDays());

        // Period measures calendar spans; adding months aligns to the target month end
        System.out.println("start.plus(span): " + start.plus(span));
        System.out.println("start.plusMonths(1): " + start.plusMonths(1));

        // normalized 只把月份折算成年,日不会折算
        System.out.println("14 months normalized: " + Period.ofMonths(14).normalized());

        // Period 没有固定秒数;需要精确时长时用 Duration
        System.out.println("two weeks from start: " + start.plus(Period.ofWeeks(2)));
    }
}

How it works

Period Measures Calendar Date Spans comes down to the class Main and the function main.

Using it

The run emits 6 labeled sections — span:, years=, start.plus(span):, start.plusMonths(1):, 14 months normalized:, two weeks from start: — one per step.

Key statements

LocalDate start = LocalDate.of(2024, 1, 31);
LocalDate end = LocalDate.of(2024, 3, 31);
Period span = Period.between(start, end);

Interactive Tools for This Topic

FAQ

What does Period Measures Calendar Date Spans print when run?
Invoke the file as-is — the `span:`, `years=`, `start.plus(span):` prefixes identify which step printed each line.