Adding month to specific day of month with java.time
Set the day of month to min(selectedDayOfMonth, lastDayOfNextMonth)
public static LocalDate next(LocalDate current, int selectedDayOfMonth) {
LocalDate next = current.plusMonths(1);
return next.withDayOfMonth(Math.min(selectedDayOfMonth, next.lengthOfMonth()));
}
Usage:
public static void test(int selectedDayOfMonth) {
LocalDate date = LocalDate.of(2001, Month.JANUARY, selectedDayOfMonth);
System.out.println(date);
for (int i = 0; i < 5; i++) {
date = next(date, selectedDayOfMonth);
System.out.println(date);
}
System.out.println();
}
Output for test(4)
:
2001-01-04
2001-02-04
2001-03-04
2001-04-04
2001-05-04
2001-06-04
Output for test(29)
:
2001-01-29
2001-02-28
2001-03-29
2001-04-29
2001-05-29
2001-06-29
Output for test(31)
:
2001-01-31
2001-02-28
2001-03-31
2001-04-30
2001-05-31
2001-06-30