formatShortInputToDateTime method

DateTime formatShortInputToDateTime({
  1. String? specificFormat,
})

Parses a short format date string into DateTime.

Supported formats (without intl):

  • 'dd/MM', 'dd-MM' → year defaults to current year
  • 'MM/dd', 'MM-dd' → year defaults to current year

Implementation

DateTime formatShortInputToDateTime({String? specificFormat}) {
  final format = specificFormat ?? 'dd/MM';
  final now = DateTime.now();
  final sep = format.contains('/') ? '/' : '-';

  try {
    switch (format) {
      case 'dd/MM':
      case 'dd-MM': {
        final parts = split(sep);
        if (parts.length != 2) throw FormatException('Invalid date string: $this');
        final day = int.parse(parts[0]);
        final month = int.parse(parts[1]);
        return DateTime(now.year, month, day);
      }
      case 'MM/dd':
      case 'MM-dd': {
        final parts = split(sep);
        if (parts.length != 2) throw FormatException('Invalid date string: $this');
        final month = int.parse(parts[0]);
        final day = int.parse(parts[1]);
        return DateTime(now.year, month, day);
      }
      default:
        throw UnimplementedError('Format $format not supported without intl');
    }
  } catch (e) {
    if (e is FormatException || e is UnimplementedError) rethrow;
    throw FormatException('Invalid short date string: $this for format $format');
  }
}