Search code examples
datetimedartflutterstring-formatting

Dart / Flutter default date format


I am trying to format DateTime result and display it to the user in user's current device locale.

Currently I can either display entire DateTime such as following:

2018-10-08 16:08:37.464112

Or by specifying exact format like this:

DateFormat("dd.MM.yyyy").format(DateTime.now())

which results in following:

08.10.2018

My problem with this solution is, while this format might be acceptable in EU; in e.g. US (and many other countries) they are used to a different Date format, e.g.

10/08/2018

My question is: how to return only Date (not time) to user in their current locale's format?

Answer:
One needs to retrieve current locale and pass it to the format function. I am using custom localizations class, yet with out of the box solution it would look like this:

DateFormat.yMMMd(Localizations.localeOf(context)).format(result);

Solution

  • You can pass a locale to DateFormat like

    format = DateFormat.yMMMd("en_US");
    

    See also