← 中文资源

简体中文版本

解析与格式化 ISO 8601 时长

ISO-8601 时长文本与 Duration 互转:parse 解析 PT2H45M30S,plusMinutes 运算后 toString 序列化,toHoursPart 等拆组件,toSeconds 换单位。

阅读英文原文

实现说明

活动部件是类 DurationCodec和函数 main。

使用要点

  • 演示输出是带标签的(parsed:、extended:、hours part:),每个操作都会留下自己的一行标注。

常见问题

运行「解析与格式化 ISO 8601 时长」会打印什么?

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

核心语句

Instant start = Instant.parse("2026-11-18T08:00:00Z");
Instant end = Instant.parse("2026-11-18T09:30:00Z");
Duration fromIso = Duration.parse("PT2H45M30S");

代码示例

import java.time.Duration;
import java.time.Instant;

public class DurationCodec {

    public static void main(String[] args) {
        // parse ISO-8601 text and format Duration back to the same notation
        Duration fromIso = Duration.parse("PT2H45M30S");
        System.out.println("parsed: " + fromIso);

        // 运算后再序列化回 ISO 文本
        Duration extended = fromIso.plusMinutes(30);
        System.out.println("extended: " + extended);

        // 拆成时/分/秒组件
        System.out.println("hours part:   " + extended.toHoursPart());
        System.out.println("minutes part: " + extended.toMinutesPart());
        System.out.println("seconds part: " + extended.toSecondsPart());

        // 换算成单一单位(存库常用)
        System.out.println("total seconds: " + extended.toSeconds());

        // 两个时刻之差也是 Duration
        Instant start = Instant.parse("2026-11-18T08:00:00Z");
        Instant end = Instant.parse("2026-11-18T09:30:00Z");
        System.out.println("elapsed: " + Duration.between(start, end));
    }
}