parse static method

Time? parse(
  1. String input
)

Parses a string into a Time object.

Supports standard DateTime parsable formats (like ISO 8601). Both UTC ('Z' suffix) and local strings are parsed into local time.

Also supports time-only strings like 'HH:mm', 'HH:mm:ss', or 'HH:mm:ss.ffffff'. Important: For time-only strings, the date component is set to the current date.

Returns null if the input string cannot be parsed.

Implementation

static Time? parse(String input) {
  final trimmedInput = input.trim(); // Trim whitespace

  // Try standard DateTime parsing first
  final dateTime = DateTime.tryParse(trimmedInput)?.toLocal();
  if (dateTime != null) return Time(dateTime);

  // Handle time-only ('HH:mm', 'HH:mm:ss' or 'HH:mm:ss.ffffff')
  try {
    final dotSeparated = trimmedInput.split('.');
    final timeParts = dotSeparated[0].split(':');

    // Must have hour and minute, optionally seconds
    if (timeParts.length < 2 || timeParts.length > 3) return null;

    final hour = int.parse(timeParts[0]);
    final minute = int.parse(timeParts[1]);
    final second = timeParts.length > 2 ? int.parse(timeParts[2]) : 0;

    int millisecond = 0;
    int microsecond = 0;
    if (dotSeparated.length > 1) {
      // Correctly parse milliseconds and microseconds
      final fractional = dotSeparated[1].padRight(6, '0'); // Ensure 6 digits
      final millisStr = fractional.substring(0, 3);
      final microsStr = fractional.substring(3, 6);
      millisecond = int.parse(millisStr);
      microsecond = int.parse(microsStr);
    }

    // Use today's date with the parsed time components
    return Time(DateTime.now().copyWith(
      hour: hour,
      minute: minute,
      second: second,
      millisecond: millisecond,
      microsecond: microsecond,
    ));
  } catch (e) {
    // Catch potential parsing errors (e.g., non-integer parts)
    return null;
  }
}