LocalTime.parse constructor

LocalTime.parse(
  1. String timeString
)

Parses a time string into a LocalTime instance.

Accepted formats:

  • HH:mm
  • HH:mm:ss
  • HH:mm:ss.SSS

Throws InvalidFormatException if the format is invalid or components can't be parsed.

Example

final t1 = LocalTime.parse('08:30');
final t2 = LocalTime.parse('14:45:59');
final t3 = LocalTime.parse('06:12:03.456');

A value object representing a time of day without any date or timezone information.

LocalTime is immutable and supports operations such as:

  • Parsing from strings
  • Formatting to strings
  • Time arithmetic (addition/subtraction)
  • Comparison and equality checks

This class is useful when working with:

  • Scheduling systems
  • Time pickers
  • Representing specific times (like "08:30 AM") without a date context

Example

final time = LocalTime(14, 30); // 2:30 PM
final later = time.plusMinutes(45); // 3:15 PM
print(later); // 15:15:00

Implementation

factory LocalTime.parse(String timeString) {
  final parts = timeString.split(':');
  if (parts.length.isLessThan(2) || parts.length.isGreaterThan(3)) {
    throw InvalidFormatException('Invalid time format. Expected HH:mm, HH:mm:ss or HH:mm:ss.SSS');
  }

  final hour = int.parse(parts[0]);
  final minute = int.parse(parts[1]);

  int second = 0;
  int millisecond = 0;

  try {
    if (parts.length.equals(3)) {
      final secondParts = parts[2].split('.');
      second = int.parse(secondParts[0]);
      if (secondParts.length.equals(2)) {
        millisecond = int.parse(secondParts[1].padRight(3, '0').substring(0, 3));
      }
    }

    return LocalTime(hour, minute, second, millisecond);
  } catch (e) {
    throw InvalidFormatException('Invalid time format. Expected HH:mm, HH:mm:ss or HH:mm:ss.SSS');
  }
}