formatDate function

String formatDate(
  1. DateTime date, {
  2. String? locale,
  3. String? pattern,
  4. DateFormatStyle? style,
})

Formats a DateTime date according to locale conventions in pure Dart.

Supports named style presets (DateFormatStyle.short, DateFormatStyle.medium, DateFormatStyle.long, DateFormatStyle.full) or custom pattern tokens (yyyy, yy, MMMM, MMM, MM, M, dd, d, HH, H, hh, h, mm, ss, a).

Uses package:intl date symbols and patterns for supported locales. An unrecognized locale falls back to Bloom's small built-in formatter.

final date = DateTime(2026, 8, 23);
formatDate(date, locale: 'en-US'); // "8/23/2026"
formatDate(date, locale: 'en-GB'); // "23/08/2026"
formatDate(date, locale: 'de-DE'); // "23.08.2026"
formatDate(date, style: DateFormatStyle.long, locale: 'en-US'); // "August 23, 2026"

See also:

Implementation

String formatDate(
  DateTime date, {
  String? locale,
  String? pattern,
  DateFormatStyle? style,
}) {
  final loc = (locale ?? BloomI18n.instance.locale.value).replaceAll('_', '-');
  try {
    _ensureDateSymbols();
    final intlLocale = loc.replaceAll('-', '_');
    if (pattern != null) {
      return intl.DateFormat(pattern, intlLocale).format(date);
    }
    final formatter = switch (style ?? DateFormatStyle.short) {
      DateFormatStyle.short => intl.DateFormat.yMd(intlLocale),
      DateFormatStyle.medium => intl.DateFormat.yMMMd(intlLocale),
      DateFormatStyle.long => intl.DateFormat.yMMMMd(intlLocale),
      DateFormatStyle.full => intl.DateFormat.yMMMMEEEEd(intlLocale),
    };
    return formatter.format(date);
  } catch (_) {
    // Keep the original formatter available for unsupported locale tags.
  }
  final lang = loc.split('-').first.toLowerCase();

  if (pattern != null) {
    return _formatDateWithPattern(date, pattern, lang);
  }

  final effectiveStyle = style ?? DateFormatStyle.short;
  return _formatDateWithStyle(date, effectiveStyle, loc, lang);
}