tryParse static method

Hora? tryParse(
  1. String input,
  2. String format, {
  3. HoraLocale? locale,
  4. bool strict = false,
})

Tries to parse a date string, returns null if parsing fails.

Implementation

static Hora? tryParse(
  String input,
  String format, {
  HoraLocale? locale,
  bool strict = false,
}) {
  locale ??= Hora.globalLocale;

  try {
    final result = _parseWithFormat(input, format, locale, strict);
    if (result == null) return null;

    // Handle 12-hour format
    var adjustedHour = result.hour ?? 0;
    if (result.is12Hour && result.hour != null) {
      if (result.isPM && adjustedHour < 12) {
        adjustedHour += 12;
      } else if (!result.isPM && adjustedHour == 12) {
        adjustedHour = 0;
      }
    }

    return Hora.of(
      year: result.year ?? DateTime.now().year,
      month: result.month ?? 1,
      day: result.day ?? 1,
      hour: adjustedHour,
      minute: result.minute ?? 0,
      second: result.second ?? 0,
      millisecond: result.millisecond ?? 0,
      utc: result.isUtc,
      locale: locale,
    );
  } catch (_) {
    return null;
  }
}