convertHHMMTimeStringToTimeOfDay method
Convert HH:MM or HHMM string to TimeOfDay
Implementation
TimeOfDay convertHHMMTimeStringToTimeOfDay() {
final raw = trim();
bool isNumeric(String s) =>
s.isNotEmpty && s.codeUnits.every((c) => c >= 48 && c <= 57);
String hourStr;
String minuteStr;
if (raw.contains(':')) {
final parts = raw.split(':');
if (parts.length != 2) {
throw const FormatException(
'Unrecognized time format. Expected HH:MM or HHMM');
}
hourStr = parts[0];
minuteStr = parts[1];
} else {
// Expect HHMM or HMM (e.g. 930 for 9:30, 1230 for 12:30)
if (raw.length < 3 || raw.length > 4) {
throw const FormatException(
'Unrecognized time format. Expected HH:MM or HHMM');
}
hourStr = raw.substring(0, raw.length - 2);
minuteStr = raw.substring(raw.length - 2);
}
if (!isNumeric(hourStr) || !isNumeric(minuteStr)) {
throw const FormatException(
'Unrecognized time format. Expected digits only');
}
if (hourStr.length > 2 || minuteStr.length != 2) {
throw const FormatException(
'Unrecognized time format. Expected HH:MM or HHMM');
}
final hour = int.parse(hourStr);
final minute = int.parse(minuteStr);
return TimeOfDay(hour: hour, minute: minute);
}