What it is and why to use it
A calendar month can have different numbers of days. Period represents date-based years, months and days and is appropriate for rules such as adding a month to an invoice date. Duration instead models a time-based amount in seconds and nanoseconds; they answer different questions.
How it works
LocalDate is a date without time of day or zone. Adding a month adjusts an invalid target day to the last valid day of the resulting month. Period.between calculates a calendar difference; its getDays component is not necessarily the total elapsed number of days.
Common mistakes and limitations
Do not approximate every month as 30 days. Repeatedly adding one month can differ from adding several months at once after a day has been adjusted. Use a day-count operation when total days are the actual requirement.
Try it and keep learning
Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.
Syntax
date.plus(Period.ofMonths(1)); Period.between(start, end);Examples
Calendar Amounts with Period
Complete Main.java example — Java 17 or later, without preview features.
import java.time.LocalDate;
import java.time.Period;
public class Main {
public static void main(String[] args) {
LocalDate invoice = LocalDate.of(2024, 1, 31);
System.out.println(invoice.plus(Period.ofMonths(1)));
Period interval = Period.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 3, 1));
System.out.println(interval);
}
}- January 31 plus one calendar month targets February, which has 29 days in 2024.
- The result adjusts to February 29 rather than adding a fixed number of seconds.
- The two first-of-month dates are two months apart, represented as ISO period P2M. A billing rule should define this end-of-month behaviour explicitly.
- Expected output: 2024-02-29 P2M
Best practices
- Separate calendar rules from elapsed-time measurements.
- Test leap years and end-of-month boundaries.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification