convertTo12HourTimeOfDay method
Convert 12-hour format string (e.g., "2:30 PM") to TimeOfDay
Implementation
TimeOfDay convertTo12HourTimeOfDay() {
final raw = trim().toUpperCase();
bool isNumeric(String s) =>
s.isNotEmpty && s.codeUnits.every((c) => c >= 48 && c <= 57);
if (!(raw.endsWith('AM') || raw.endsWith('PM'))) {
throw const FormatException(
'Invalid 12-hour time format. Expected format: H:MM AM/PM');
}
final period = raw.substring(raw.length - 2); // AM or PM
String timePart = raw.substring(0, raw.length - 2).trim(); // remove period
if (!timePart.contains(':')) {
throw const FormatException(
'Invalid 12-hour time format. Missing colon.');
}
final parts = timePart.split(':');
if (parts.length != 2) {
throw const FormatException(
'Invalid 12-hour time format. Expected single colon.');
}
final hourStr = parts[0];
final minuteStr = parts[1];
if (!isNumeric(hourStr) ||
!isNumeric(minuteStr) ||
minuteStr.length != 2 ||
hourStr.length > 2) {
throw const FormatException(
'Invalid 12-hour time format. Non-numeric components.');
}
int hour = int.parse(hourStr);
int minute = int.parse(minuteStr);
// Convert to 24-hour format
if (period == 'AM') {
if (hour == 12) hour = 0; // 12 AM is 00:00
} else {
// PM
if (hour != 12) hour += 12; // Add 12 except for 12 PM
}
return TimeOfDay(hour: hour, minute: minute);
}