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.
Code
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
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.