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

  1. Start with January 1, 2024
  2. Do this Add a month
  3. Result February 1, 2024
The first day exists in both months.

Apply it to a real problem

  1. Start with January 31 renewal dates
  2. Do this Move forward one calendar month
  3. Result Feb 28 in 2023, Feb 29 in 2024
The date moves to the final valid day when February has no 31st.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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));
        }
    }
}
Output
2023-02-28
2024-02-29

Official Java documentation