toTimeOfDay12 method

TimeOfDay toTimeOfDay12()

"2:30 PM", "02:30pm", "2:30PM" → TimeOfDay (12-hour format)

Implementation

TimeOfDay toTimeOfDay12() {
  final cleaned = trim().replaceAll(' ', '');
  final regExp = RegExp(
    r'^(\d{1,2}):(\d{2})(AM|PM|am|pm)$',
    caseSensitive: false,
  );
  final match = regExp.firstMatch(cleaned);
  if (match == null) {
    throw FormatException('Invalid 12-hour time format: $this');
  }

  var h = int.parse(match.group(1)!);
  final m = int.parse(match.group(2)!);
  final period = match.group(3)!.toUpperCase();

  if (h == 12) h = 0;
  if (period == 'PM') h += 12;

  return TimeOfDay(hour: h, minute: m);
}