实现说明
plusMonths 月末钳制可以归结为类 BillingDates和函数 main。
使用要点
- 演示输出是带标签的(
jan 31 + 1 month ->、feb 28 + 1 month ->、leap + 1 year ->),每个操作都会留下自己的一行标注。
常见问题
运行「plusMonths 月末钳制」会打印什么?
整个文件跑完,输出行以 jan 31 + 1 month ->、feb 28 + 1 month ->、leap + 1 year -> 这类前缀开头。
核心语句
LocalDate afterLeap = LocalDate.of(2024, 2, 29).plusYears(1);
LocalDate jan31 = LocalDate.of(2026, 1, 31);
YearMonth cycle = YearMonth.from(jan31);
代码示例
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());
}
}