formatTimeOfDay static method

String formatTimeOfDay(
  1. TimeOfDay? timeOfDay, {
  2. bool formatTo12Hr = true,
})

Formats a TimeOfDay to a string.

Parameters:

  • timeOfDay: The time to format (returns empty string if null)
  • formatTo12Hr: Whether to use 12-hour format with AM/PM. Defaults to true

Returns formatted time string (e.g., "02:30 PM" or "14:30").

Implementation

static String formatTimeOfDay(TimeOfDay? timeOfDay,
    {bool formatTo12Hr = true}) {
  if (timeOfDay == null) return '';
  String addLeadingZeroIfNeeded(int value) {
    if (value < 10) {
      return '0$value';
    }
    return value.toString();
  }

  int hr = formatTo12Hr ? timeOfDay.hour % 12 : timeOfDay.hour;

  final String hourLabel = addLeadingZeroIfNeeded(hr);
  final String minuteLabel = addLeadingZeroIfNeeded(timeOfDay.minute);

  String suffix = formatTo12Hr ? (timeOfDay.hour > 11 ? ' PM' : ' AM') : '';

  return '$hourLabel:$minuteLabel$suffix';
}