toTimeOfDay method

TimeOfDay toTimeOfDay(
  1. BuildContext context
)

Parses a time string that was created with timeOfDay.format(context) Supports both 12-hour (e.g. "2:30 PM") and 24-hour (e.g. "14:30") formats

Implementation

TimeOfDay toTimeOfDay(BuildContext context) {
  if (isEmpty) {
    throw const FormatException('Time string is empty');
  }

  final is24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat;

  final trimmed = trim();

  if (is24HourFormat) {
    // 24-hour format: "14:30" or "09:05"
    final regExp = RegExp(r'^(\d{1,2}):(\d{2})$');
    final match = regExp.firstMatch(trimmed);
    if (match == null) {
      throw FormatException('Invalid 24-hour time format: $trimmed');
    }
    return TimeOfDay(
      hour: int.parse(match.group(1)!),
      minute: int.parse(match.group(2)!),
    );
  } else {
    // 12-hour format: "2:30 PM", "11:45 AM", etc.
    final regExp = RegExp(r'^(\d{1,2}):(\d{2})\s?([AaPp][Mm])$');
    final match = regExp.firstMatch(trimmed);
    if (match == null) {
      throw FormatException('Invalid 12-hour time format: $trimmed');
    }

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

    if (hour == 12) {
      hour = period == 'AM' ? 0 : 12;
    } else if (period == 'PM') {
      hour += 12;
    }

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