Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 932
Robert J. Avatar asked Oct 08 '18 16:10

Robert J.


People also ask

What is date format Flutter?

DateFormat is for formatting and parsing dates in a locale-sensitive manner. It allows the user to choose from a set of standard date time formats as well as specify a customized pattern under certain locales. Date elements that vary across locales include month name, week name, field order, etc.

How do you implement date format in Flutter?

To format DateTime in Flutter using a standard format, you need to use the intl library and then use the named constructors from the DateFormat class. Simply write the named constructor and then call the format() method with providing the DateTime.


1 Answers

I know this is already answered, but in case someone wants to use the actual device locale and not a hard-coded one:

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

Important, you need to pass a String and not a Locale object here.

If you want to have a custom date format, then you need to create your own switch/case based on all the locales you want to support.

like image 98
Miguel Beltran Avatar answered Oct 06 '22 23:10

Miguel Beltran