cTimeOfDayToString method
An extension for nullable TimeOfDay objects, providing a method to convert them to a formatted string in AM/PM format or display 'Invalid date' if the TimeOfDay object is null.
This extension is useful for converting a nullable TimeOfDay object to a user-friendly string representation.
Example usage:
TimeOfDay? timeOfDay = TimeOfDay(hour: 14, minute: 30);
String formattedTime = timeOfDay.cTimeOfDayToString();
print(formattedTime); // Output: "2:30 PM"
timeOfDay = null;
formattedTime = timeOfDay.cTimeOfDayToString();
print(formattedTime); // Output: "Invalid date"
Implementation
String cTimeOfDayToString() {
if (this != null) {
final now = DateTime.now();
final dateTime = DateTime(
now.year,
now.month,
now.day,
this!.hour,
this!.minute,
);
final formatter =
DateFormat.jm(); // This will format it into AM/PM format
return formatter.format(dateTime);
} else {
return 'Invalid date';
}
}