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.
Code
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
ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.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 Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.