stringToDateTime function

DateTime stringToDateTime(
  1. String dateString
)

Converts the string dateString into a DateTime instance. Throws ArgumentsError on syntax error(s).

Implementation

DateTime stringToDateTime(String dateString) {
  RegExpMatch? matcher;
  int year, month, day;
  var minute = 0, hour = 0, second = 0;
  if (!dateString.contains('-')) {
    matcher = _regExprDate1.firstMatch(dateString);
  } else {
    matcher = _regExprDateTime2.firstMatch(dateString);
    if (matcher != null) {
      hour = int.parse(matcher.group(4)!);
      minute = int.parse(matcher.group(5)!);
      if (matcher.group(6) != null) {
        second = int.parse(matcher.group(6)!);
      }
    }
  }
  if (matcher == null) {
    throw ArgumentError('not a date or date time: $dateString');
  }
  final val = matcher.group(1);
  year = val == null || val == ''
      ? DateTime.now().year
      : int.parse(matcher.group(1)!);
  month = int.parse(matcher.group(2)!);
  day = int.parse(matcher.group(3)!);
  var rc = DateTime(year, month, day, hour, minute, second);
  return rc;
}