tryParse static method

XPathDateTime? tryParse(
  1. String value, [
  2. XPathType type = xsDateTime
])

Attempts to parse a string representation of a date/time.

Implementation

static XPathDateTime? tryParse(String value, [XPathType type = xsDateTime]) {
  if (type == xsDate) return tryParseDate(value);
  if (type == xsTime) return tryParseTime(value);
  if (type == xsGYearMonth) return tryParseYearMonth(value);
  if (type == xsGYear) return tryParseYear(value);
  if (type == xsGMonthDay) return tryParseMonthDay(value);
  if (type == xsGMonth) return tryParseMonth(value);
  if (type == xsGDay) return tryParseDay(value);

  final match = _dateTimeRegExp.firstMatch(value);
  if (match == null) return null;

  final tz = _parseTimezoneGroup(match);
  if (!tz.valid) return null;
  final offset = tz.offset;
  if (type == xsDateTimeStamp && offset == null) return null;

  final yr = int.tryParse(match.namedGroup('year')!);
  if (yr == null) return null;

  final mo = int.parse(match.namedGroup('month')!);
  final dy = int.parse(match.namedGroup('day')!);
  final hr = int.parse(match.namedGroup('hour')!);
  final mn = int.parse(match.namedGroup('minute')!);
  final scDouble = double.parse(match.namedGroup('second')!);
  final (:second, :millisecond, :microsecond) = _splitSeconds(scDouble);

  if (!_validateDateTime(yr, mo, dy, hr, mn, scDouble)) return null;

  if (hr == 24) {
    final normalizedDate = DateTime.utc(
      yr,
      mo,
      dy,
    ).add(const Duration(days: 1));
    return XPathDateTime(
      normalizedDate.year,
      normalizedDate.month,
      normalizedDate.day,
      0,
      0,
      0,
      0,
      0,
      offset,
      type,
    );
  }

  return XPathDateTime(
    yr,
    mo,
    dy,
    hr,
    mn,
    second,
    millisecond,
    microsecond,
    offset,
    type,
  );
}