formatDateTime function
String
formatDateTime(
- DateTime dateTime, {
- String? locale,
- String? pattern,
- DateFormatStyle? style,
Formats a DateTime date and time according to locale conventions in pure Dart.
Combines localized date formatting with appropriate 12-hour (AM/PM) or 24-hour time formatting based on locale rules.
When locale is omitted, defaults to the active BloomI18n.instance.locale value.
final dt = DateTime(2026, 8, 23, 14, 30);
formatDateTime(dt, locale: 'en-US'); // "8/23/2026, 2:30 PM"
formatDateTime(dt, locale: 'fr-FR'); // "23/08/2026 14:30"
See also:
- formatDate, for date-only formatting.
- formatRelativeTime, for relative time formatting ("5 minutes ago").
- localizedDateTime, top-level convenience shorthand.
Implementation
String formatDateTime(
DateTime dateTime, {
String? locale,
String? pattern,
DateFormatStyle? style,
}) {
final intlLocale =
(locale ?? BloomI18n.instance.locale.value).replaceAll('-', '_');
try {
_ensureDateSymbols();
if (pattern != null) {
return intl.DateFormat(pattern, intlLocale).format(dateTime);
}
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.add_jm().format(dateTime);
} catch (_) {
// Keep the original formatter for locale tags intl does not recognize.
}
if (pattern != null) {
final loc =
(locale ?? BloomI18n.instance.locale.value).replaceAll('_', '-');
final lang = loc.split('-').first.toLowerCase();
return _formatDateWithPattern(dateTime, pattern, lang);
}
final datePart = formatDate(dateTime, locale: locale, style: style);
final loc = (locale ?? BloomI18n.instance.locale.value).replaceAll('_', '-');
final lang = loc.split('-').first.toLowerCase();
final h24 = dateTime.hour.toString().padLeft(2, '0');
final min = dateTime.minute.toString().padLeft(2, '0');
final h12 = (dateTime.hour == 0
? 12
: (dateTime.hour > 12 ? dateTime.hour - 12 : dateTime.hour))
.toString();
final ampm = dateTime.hour < 12 ? 'AM' : 'PM';
if (['en-us', 'en-ca'].contains(loc.toLowerCase())) {
return '$datePart, $h12:$min $ampm';
} else if (['fr', 'de', 'es', 'it', 'ru'].contains(lang)) {
return '$datePart $h24:$min';
}
return '$datePart $h24:$min';
}