convertToTimeOfDay static method
Converts formatted time string to TimeOfDay object
Parses a formatted time string (e.g., "10:30 z", "10:30 ʟ", or "10:30") into a TimeOfDay object.
Process:
- Remove timezone suffix ("z", "L", or "ʟ") and whitespace
- Split on colon separator
- Parse hours and minutes
- Validate ranges (0-23 hours, 0-59 minutes)
- Return TimeOfDay or error
Examples:
- "10:30 z" → (TimeOfDay(10, 30), null)
- "10:30 ʟ" → (TimeOfDay(10, 30), null)
- "10:30" → (TimeOfDay(10, 30), null)
- "25:00 z" → (null, "Invalid time: 25:00")
- "invalid" → (null, "Invalid format: invalid")
timeString - Formatted time string with optional timezone suffix
Returns tuple of (TimeOfDay?, String?) where second element is error message
Implementation
static TimeOfDay convertToTimeOfDay(String timeString,
{bool isUtc = true,
(DateTime?, TimeOfDay?) defaultTime = const (null, null)}) {
final dfT =
defaultTime.$1 ?? (isUtc ? DateTime.now().toUtc() : DateTime.now());
var timeOfDay = TimeOfDay(hour: dfT.hour, minute: dfT.minute);
if (timeString != 'null' && timeString.isNotEmpty) {
// Remove timezone suffixes ('z', 'L', or 'ʟ') and trim any whitespace
timeString = timeString
.replaceAll(' z', '')
.replaceAll(' L', '')
.replaceAll(' ʟ', '')
.trim();
// Split the string into hours and minutes
final parts = timeString.split(':');
if (parts.length == 2) {
var hours = int.tryParse(parts[0]);
var minutes = int.tryParse(parts[1]);
// Validate hours and minutes
if (hours == null || hours < 0 || hours > 23) {
hours = defaultTime.$2 != null ? defaultTime.$2!.hour : dfT.hour;
}
if (minutes == null || minutes < 0 || minutes > 59) {
minutes =
defaultTime.$2 != null ? defaultTime.$2!.minute : dfT.minute;
}
timeOfDay = TimeOfDay(hour: hours, minute: minutes);
}
}
// Create a DateTime object for today with the specified time
return timeOfDay;
}