Iso8601Duration class final

An ISO 8601 duration: P3Y6M4DT12H30M5S, or the week form P2W. Standard: ISO 8601.

Parse, don't validate: dart:core's Duration cannot express months or years, nor read this format. Holds components rather than one scalar, because a month has no length until anchored.

Note

P1M is one month and PT1M is one minute. The T is what separates them, so it is required before a time component and refused without one.

The week form is exclusive, so P1Y2W is refused, and at least one component is required, so PT0S is the zero duration and P is not. Only the smallest component may carry a fraction. Negative durations are refused: ISO 8601-1 has no sign.

Normalisation on parse: a decimal comma becomes a point and zero components collapse, so P1Y0M and P1Y are one value. iso8601 is the canonical form.

final span = Iso8601Duration.tryParse('P1Y2M3DT4H')!;
print(span.iso8601); // P1Y2M3DT4H
print(span.months); // 2
print(
  span.toDuration(from: Date.of(2026, 1, 31).getOrThrow()),
); // 10252:00:00.000000  (427 days and 4 hours)
print(
  Iso8601Duration.tryParse('P1M')!.toDuration(from: Date.of(2026, 2).getOrThrow()),
); // 672:00:00 (28 days)
print(Iso8601Duration.tryParse('PT1M')!.iso8601); // PT1M  (a minute; P1M is a month)
print(Iso8601Duration.parse('P1Y2W').reasonOrNull?.message);
// the week form PnW cannot carry a "Y" component too
Annotations
  • @immutable

Properties

days → int
Whole days.
final
fraction → ({Iso8601DurationComponent component, double value})?
The fractional part and the component carrying it, or null when the duration is whole. Always the smallest component present, since ISO 8601 allows a fraction nowhere else.
final
hashCode → int
The hash code for this object.
no setteroverride
hours → int
Whole hours.
final
iso8601 → String
The canonical text, P3Y6M4DT12H30M5S. Round-trips through parse.
no setter
minutes → int
Whole minutes.
final
months → int
Whole months.
final
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
seconds → int
Whole seconds.
final
weeks → int
Whole weeks. Non-zero only in the week form, where every other component is zero.
final
years → int
Whole years.
final

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toDuration({required Date from}) → Duration
This duration as a Duration, resolved against from.
toString() → String
A string representation of this object.
override

Operators

operator ==(Object other) → bool
The equality operator.
override

Static Methods

parse(String input) → ParseOutcome<Iso8601DurationFailure, Iso8601Duration>
Parses input as an ISO 8601 duration, reporting the Iso8601DurationFailure saying which rule broke.
tryParse(String input) → Iso8601Duration?
Parses input as an ISO 8601 duration, or returns null when it is not one. See the type docs for the normalisation applied.