Period Parses Text And Adds Without Carry

Parse P1Y2M3W4D text where weeks fold into days, add periods component-wise with no normalization, and normalize only when months should carry into years.

JavaData Integrity

Code

snippet
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);
    }
}

What the code does

Period Parses Text And Adds Without Carry keeps everything in the class SubscriptionTerms and the function main.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

The run emits 5 labeled sections — years:, sprint:, grown:, normalized:, sum: — one per step.

Statements that matter

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");

Interactive Tools for This Topic

FAQ

What does Period Parses Text And Adds Without Carry print when run?
Run it as a complete program — the output lines carry labels such as `years:`, `sprint:`, `grown:`.