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,
}) {
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';
}