Formatting Dates in Flutter
I wanted to internationalize dates to French. Here's how I used the intl package.
All the information has already been documented in https://pub.dev/packages/intl, but I will summarize each element that I needed as well as some gotchas.
First I simply created my formatter like so: DateFormat.Hm("fr")
. But this threw an exception because the date formatting locales haven't been loaded yet. You have to first call the asynchronous initializeDateFormatting(locale)
which returns Future<void>.
Here's how to set it up properly:
import 'package:intl/date_symbol_data_local.dart';
const locale = "fr";
DateFormat timeFormat;
initializeDateFormatting(locale).then((_) {
timeFormat = DateFormat.Hm(locale);
});
There are two important things to note:
- You want to import
date_symbol_data_local
, notdate_symbol_data_local_file
nordate_symbol_data_local_http
. - Simply initializing date formatting with a locale does not make it the default locale. You still have to specify the locale when instantiating a formatter.
Last useful tidbit, to make a formatter that combines date and time, you do it like so:
final dateTimeFormat = DateFormat.yMMMMEEEEd(locale).add_Hm();
And here's a properly formatted date time in French:
print(dateTimeFormat.format(DateTime(2019, 06, 06)));
==> 'jeudi 6 juin 2019 00:00'