← 中文资源

简体中文版本

Duration 分量读取与人类可读预算

toXxxPart 给出"去掉更大单位后的余数":toHours 是总小时而 toHoursPart 是天内余下的小时;报表文案按 days/hours/minutes/seconds 分量拼接。

阅读英文原文

实现说明

Duration 分量读取与人类可读预算可以归结为类 SLAReport和函数 main。

使用要点

  • 跑完文件,输出里会留下标记——total hours:、days:、hours:。

常见问题

运行「Duration 分量读取与人类可读预算」会打印什么?

运行文件本身,total hours:、days:、hours: 这些前缀各对应一段演示逻辑。

核心语句

Duration budget = Duration.parse("P1DT2H30M15S");
Duration wait = Duration.ofSeconds(150);

代码示例

import java.time.Duration;

public class SLAReport {

    public static void main(String[] args) {
        // 1 天 2 小时 30 分 15 秒的 SLA 预算
        Duration budget = Duration.parse("P1DT2H30M15S");

        // toHours() 是总小时数:1 天折成 24 + 2 = 26
        System.out.println("total hours: " + budget.toHours());

        // toXxxPart 是"分量":除掉更大单位后的余数,用于 1d 02:30:15 这种展示
        System.out.println("days:    " + budget.toDaysPart());
        System.out.println("hours:   " + budget.toHoursPart());
        System.out.println("minutes: " + budget.toMinutesPart());
        System.out.println("seconds: " + budget.toSecondsPart());

        // toSeconds() 仍是总数:150 秒的 toSecondsPart 是余数 30
        Duration wait = Duration.ofSeconds(150);
        System.out.println("total seconds: " + wait.toSeconds());
        System.out.println("seconds part: " + wait.toSecondsPart());

        // 拼一段 "2d 03:05:09" 风格的报表文案
        String rendered = "%dd %02d:%02d:%02d".formatted(
                budget.toDaysPart(), budget.toHoursPart(),
                budget.toMinutesPart(), budget.toSecondsPart());
        System.out.println("rendered: " + rendered);
    }
}