1

I'm trying to format dates according to the device's locale. If you have "standard" locales like en_US, de_DE and so on, this is no problem. But if the user has set his phone language to e.g. englisch (en) and the region to e.g. Germany (DE), the locale will be the following en_DE (not standard locale).

If I try now to format a date with this locale, it will always use US formatting (I think because auf the language part en):

String date = DateFormat.yMd('en_DE').format(DateTime.now());
print(date); // 7/13/2022

If I use only the region part DE, this will work for DE:

String date = DateFormat.yMd('DE').format(DateTime.now());
print(date); // 13.07.2022

But for the locale en_US this will not work:

String date = DateFormat.yMd('US').format(DateTime.now()); // Invalid argument(s): Invalid locale "US"

How can I format the date according to the region part of the locale?

justchris
  • 123
  • 8

1 Answers1

1

You can do it in a try catch

String date = "";
String locale = 'en_US';
try{
 date = DateFormat.yMd('${locale.subString(3)}').format(DateTime.now());
}catch(e){
 date = DateFormat.yMd('$locale').format(DateTime.now());
}
print(date);
Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • Not quite. If I change the locale to `en_CH` (CH = Switzerland), it tries to format the date with `CH`, which is not a valid language code so it produces an error and the catch block will be triggered. In the catch it formats the date with `en_CH` and this will format the date with `US` formatting `7/13/2022` again. – justchris Jul 16 '22 at 16:58
  • Yeah but only if ch isn't able to format it will take the us format – Kaushik Chandru Jul 16 '22 at 17:10
  • So it gives priority to the region. Then if it fails it takes the language – Kaushik Chandru Jul 16 '22 at 17:17
  • Yeah but that's not what I want. I primarily care about the region, not the language. If I set my phone's language to english and my region to switzerland, the date should be formatted like that `16.07.2022`. I need to figure out the defaults language of a region somehow. – justchris Jul 16 '22 at 17:44
  • Got it. Try this one https://stackoverflow.com/questions/49807687/how-to-load-all-dart-dateformat-locale-in-flutter – Kaushik Chandru Jul 16 '22 at 17:59