parseWithNumericTz function

DateTime parseWithNumericTz(
  1. String value,
  2. ParseInfo pi
)

Parse a dateTime string with a numeric TZ like +300

Dart do not support parsing of Z on DateFormat and always will default to UTC this is a hacky way to move the date offset manually. this will not use DST or any other external information, just the offset

reference: https://github.com/dart-lang/intl/issues/19

Implementation

DateTime parseWithNumericTz(String value, ParseInfo pi) {
  try {
    final tmp = DateFormat(pi.format).parseUtc(value);
    final matchStr = pi.rgx.matchAsPrefix(value);

    if (matchStr != null && matchStr.group(2) != null) {
      final offsetStr = matchStr.group(2)!;
      final isNegative = offsetStr.startsWith('-');
      final duration = Duration(
        hours: int.parse(offsetStr.substring(1, 3)),
        minutes: int.parse(offsetStr.substring(3)),
      );

      return isNegative ? tmp.add(duration) : tmp.subtract(duration);
    }

    return tmp;
  } on FormatException catch (e) {
    assert(() {
      stderr.writeln('Debug: parseWithNumericTz error for [$value] with [${pi.format}]: $e');
      return true;
    }(), 'parseWithNumericTz failed');
    rethrow;
  }
}