HTime.fromString constructor

HTime.fromString(
  1. String s
)

Parse from string fomat 'hh:mm:ss.FF' or raise ParseError.

Implementation

factory HTime.fromString(String s) {
  final err = ParseError(s);
  int hour, min, sec, ms;
  try {
    hour = int.parse(s.substring(0, 2));
  } catch (e) {
    throw ParseError('Invalid hours: $s');
  }
  if (s.codeUnitAt(2) != COLON_CHAR) throw err;
  try {
    min = int.parse(s.substring(3, 5));
  } catch (e) {
    throw ParseError('Invalid minutes: $s');
  }
  if (s.codeUnitAt(5) != COLON_CHAR) throw err;
  try {
    sec = int.parse(s.substring(6, 8));
  } catch (e) {
    throw ParseError('invalid seconds: $s');
  }
  if (s.length == 'hh:mm:ss'.length) return HTime(hour, min, sec);
  if (s.codeUnitAt(8) != PERIOD_CHAR) throw err;
  ms = 0;
  int pos = 9;
  int places = 0;

  // HTime only stores ms precision, so truncate anything after that
  while (pos < s.length && places < 3) {
    ms = (ms * 10) + (s.codeUnitAt(pos) - '0'.codeUnitAt(0));
    ++pos;
    ++places;
  }

  switch (places) {
    case 1:
      ms *= 100;
      break;
    case 2:
      ms *= 10;
      break;
    case 3:
      break;
    default:
      throw ParseError('Too much fractional precision: $s');
  }

  return HTime(hour, min, sec, ms);
}