← 中文资源

简体中文版本

Period 解析与无进位相加

Period.parse 把周转成天(P1Y2M3W4D 即 1 年 2 月 25 天),plus 分量相加不做进位(13 个月不会变 1 年 1 月),normalized() 才折年。

阅读英文原文

实现说明

真正干活的是类 SubscriptionTerms和函数 main,其余都是接线。

使用要点

  • 跑完文件,输出里会留下标记——years:、sprint:、grown:。

常见问题

运行「Period 解析与无进位相加」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 years:、sprint:、grown: 标签标明各步骤。

核心语句

Period sum = Period.of(1, 6, 3).plus(Period.of(2, 2, 2));
Period grown = Period.of(1, 11, 0).plusMonths(2);
Period trial = Period.parse("P1Y2M3W4D");

代码示例

import java.time.Period;

public class SubscriptionTerms {

    public static void main(String[] args) {
        // 周不是存储单位:解析时直接乘 7 并进天
        Period trial = Period.parse("P1Y2M3W4D");
        System.out.println("years: " + trial.getYears()
                + " months: " + trial.getMonths()
                + " days: " + trial.getDays());   // 3 周 + 4 天 = 25 天

        // ofWeeks 同样只存天:P28D,不保留"周"这个分量
        Period sprint = Period.ofWeeks(4);
        System.out.println("sprint: " + sprint);

        // plus 分量各自相加,不做进位:11 个月 + 2 个月 = 13 个月
        Period grown = Period.of(1, 11, 0).plusMonths(2);
        System.out.println("grown: " + grown);      // P1Y13M,没有进位成 2 年 1 月

        // normalized() 才会把超出 12 的月份折进年
        System.out.println("normalized: " + grown.normalized());

        // 两个 Period 相加也是分量对齐,days 不动
        Period sum = Period.of(1, 6, 3).plus(Period.of(2, 2, 2));
        System.out.println("sum: " + sum);
    }
}