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.
Code
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
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.