Parse And Format ISO 8601 Durations

Parse ISO-8601 duration text like PT2H45M30S into a Duration, extend it, read back hour/minute/second parts, and convert to a single unit.

JavaData Integrity

Code

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

How it works

Parse And Format ISO 8601 Durations is built around the class DurationCodec and the function main.

Caveats

  • No external surface: all behavior comes from the standard library.

Putting it to use

The primary signature is public static void main(String[] args)

The demo output is labeled (parsed:, extended:, hours part:), so every printed line maps back to its originating operation.

Core lines

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

Interactive Tools for This Topic

FAQ

What does Parse And Format ISO 8601 Durations print when run?
The script runs standalone; its 7 labeled outputs include `parsed:`, `extended:`, `hours part:`.