PlusMonths Month-End Clamping
plusMonths and plusYears clamp to the last valid day instead of overflowing into the next month, and the clamp is not reversible when months are added back.
Code
import java.time.LocalDate;
import java.time.YearMonth;
public class BillingDates {
public static void main(String[] args) {
LocalDate jan31 = LocalDate.of(2026, 1, 31);
// month-end clamping (钳制):加一个月停靠在 2 月 28 日,不会溢出成 3 月 2/3 日
LocalDate feb = jan31.plusMonths(1);
System.out.println("jan 31 + 1 month -> " + feb);
// 钳制不可逆:再加一个月停在 3 月 28 日,不会回到 31 日
LocalDate march = feb.plusMonths(1);
System.out.println("feb 28 + 1 month -> " + march);
// 闰日同样钳制:2024-02-29 加一年落在 2025-02-28
LocalDate afterLeap = LocalDate.of(2024, 2, 29).plusYears(1);
System.out.println("leap + 1 year -> " + afterLeap);
// 需要真正的月末日期时,用 YearMonth.atEndOfMonth 显式表达意图
YearMonth cycle = YearMonth.from(jan31);
System.out.println("explicit end -> " + cycle.atEndOfMonth());
}
}How it works
The working surface is the class BillingDates and the function main — everything else is wiring.
Caveats
- Every behavior here comes straight out of the standard library.
Putting it to use
Entry signature: public static void main(String[] args)
The run tags its output — jan 31 + 1 month ->, feb 28 + 1 month ->, leap + 1 year -> — when the file runs.
Core lines
LocalDate afterLeap = LocalDate.of(2024, 2, 29).plusYears(1);
LocalDate jan31 = LocalDate.of(2026, 1, 31);
YearMonth cycle = YearMonth.from(jan31);
Interactive Tools for This Topic
FAQ
- What does PlusMonths Month-End Clamping print when run?
- No setup needed: run the file and look for labeled lines like `jan 31 + 1 month ->`, `feb 28 + 1 month ->`, `leap + 1 year ->` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.