Calculate a renewal across February in Java
Adding a month keeps the day of the month when possible. If the target month is shorter, LocalDate chooses its last valid day.
A simple example
Add a month
- Start with January 1, 2024
- Do this Add a month
- Result February 1, 2024
Apply it to a real problem
- Start with January 31 renewal dates
- Do this Move forward one calendar month
- Result Feb 28 in 2023, Feb 29 in 2024
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) throws Exception {
for (int year : new int[]{2023, 2024}) {
System.out.println(LocalDate.of(year, 1, 31).plusMonths(1));
}
}
}
2023-02-28 2024-02-29