parseIsoInterval function

DateTimeRange<DateTime> parseIsoInterval(
  1. String input
)

Parses an ISO 8601 time interval into a DateTimeRange. Accepts the start/end, start/duration, and duration/end forms, separated by /. Throws a FormatException if the separator is missing, either half is malformed, both halves are durations, or start ends up after end.

Example:

parseIsoInterval('2026-01-01T00:00:00Z/P1DT12H');
// start 2026-01-01T00:00Z, end 2026-01-02T12:00Z

Audited: 2026-06-12 11:26 EDT

Implementation

DateTimeRange parseIsoInterval(String input) {
  final List<String> halves = input.trim().split('/');
  if (halves.length != 2) {
    throw FormatException('ISO interval must be two parts separated by "/"', input);
  }
  final String left = halves[0];
  final String right = halves[1];
  final bool leftIsDuration = left.startsWith('P');
  final bool rightIsDuration = right.startsWith('P');
  if (leftIsDuration && rightIsDuration) {
    throw FormatException('ISO interval cannot have two durations', input);
  }
  if (leftIsDuration) {
    final DateTime end = _parseDateTime(right);
    return _range(_parseIsoDuration(left).applyTo(end, -1), end, input);
  }
  final DateTime start = _parseDateTime(left);
  if (rightIsDuration) {
    return _range(start, _parseIsoDuration(right).applyTo(start, 1), input);
  }
  return _range(start, _parseDateTime(right), input);
}