How to get a localized date string in flutter?

Viewed 4915

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.

2 Answers

You can use second approach by passing locale in DateFormater like below code:

String locale = Localizations.localeOf(context).languageCode;
DateTime now = new DateTime.now();
String dayOfWeek = DateFormat.EEEE(locale).format(now);
String dayMonth = DateFormat.MMMMd(locale).format(now);
String year = DateFormat.y(locale).format(now);

Each named constructor of DateFormat takes a locale as an optional position parameter.

In this case, you don't even need to make your widget stateful.

After taking a look at the documentation, i believe you need to tell the package which locale you want to use. Try passing a parameter to initializeDateFormatting() with the locale string you want to use.

import 'package:intl/date_symbol_data_local.dart';

initializeDateFormatting('fr_FR', null).then((_) => runMyCode());

To get the locale from the device use:

import 'dart:io';

final String defaultLocale = Platform.localeName; // Returns locale string in the form 'en_US

font: How to get timezone, Language and County Id in flutter by the location of device in flutter?

Related