cToTimeOfDay method
Parses the string into a TimeOfDay object.
This method attempts to parse the input string in both 12-hour and 24-hour time formats and returns a TimeOfDay object if parsing is successful, or null if the string cannot be parsed as a valid time.
If the input string cannot be parsed in either format, it returns null.
Example:
String timeString = "2:30 PM";
TimeOfDay? timeOfDay = timeString.cToTimeOfDay();
if (timeOfDay != null) {
print("Parsed time: $timeOfDay");
} else {
print("Invalid time format");
}
Implementation
TimeOfDay? cToTimeOfDay() {
try {
// Attempt to parse the time using 12-hour format
final dateTime12Hour = DateFormat('h:mm a').parse((this).toUpperCase());
return TimeOfDay.fromDateTime(dateTime12Hour);
} catch (_) {
try {
// Attempt to parse the time using 24-hour format
final dateTime24Hour = DateFormat('H:mm').parse(this);
return TimeOfDay.fromDateTime(dateTime24Hour);
} catch (_) {
return null;
}
}
}