In Flutter, how do you get a properly formatted date string that matches the user's (or device's) language setting?
For example:
In English a date is commonly written as "Friday April 10", in German it's commonly written as "Freitag 10. April".
According to the docs, initializeDateFormatting()
, must be called to enable localized results from DateFormat
. In code this looks like:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
class DateTimeDisplay extends StatefulWidget {
DateTimeDisplay({Key? key}) : super(key: key);
@override
_DateTimeDisplay createState() => _DateTimeDisplay();
}
class _DateTimeDisplay extends State<DateTimeDisplay> {
@override
void initState() {
super.initState();
initializeDateFormatting().then((_) => setState(() {}));
}
@override
Widget build(BuildContext context) {
DateTime now = new DateTime.now();
String dayOfWeek = DateFormat.EEEE().format(now);
String dayMonth = DateFormat.MMMMd().format(now);
String year = DateFormat.y().format(now);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dayOfWeek, textAlign: TextAlign.center),
Text(dayMonth, textAlign: TextAlign.center),
Text(year, textAlign: TextAlign.center),
],
);
}
}
The problem is, that DateFormat.EEEE().format(now);
always returns the day in English. Same as DateFormat.MMMMd().format(now);
, which only replies the English month and date/month order.
Do you have any ideas what could be wrong here? Or how to convince flutter to return a properly localized date? Your advise is very much appreciated. Thank you.