I was struggling with date formatting in Kotlin.
Does someone know why using :
val locale = ConfigurationCompat.getLocales(Resources.getSystem().configuration).get(0)
java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT, locale).format(Date())
give me :
- In FR_fr = 08/09/2022 (expected)
- In EN_gb = 08/09/2022 (unexpected)
BUT
val currentLanguage = ConfigurationCompat.getLocales(Resources.getSystem().configuration).get(0).language
val locale = Locale(currentLanguage)
java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT, locale).format(Date())
gives me :
- In FR_fr = 08/09/2022 (expected)
- In EN_gb = 9/8/2022 (expected)
Is there a simpler way?
CodePudding user response:
In the second one, while you are doing this,
ConfigurationCompat.getLocales(Resources.getSystem().configuration).get(0).language
it will give language as en
.It will not give country variant english.It will return generic english locale.
So you should create locale like below.
val currentLanguage = ConfigurationCompat.getLocales(Resources.getSystem().configuration).get(0)
if (currentLanguage!=null) {
val currentLocale = Locale(currentLanguage.language, currentLanguage.country, currentLanguage.variant)
}
THis will create locale with en-GB in your case.
In the first one you are already getting locale object with en-GB
.
en-GB
and en
has different formats of date.
08/09/2022 : en-GB
9/8/2022 : en
en-IN
(Indian English) also will give 08/09/2022
as result.
CodePudding user response:
The reason for the different results is because
- in you first example, you work with actual
en_GB
/fr_FR
locale, - but in the second example, your locale is only
en
/fr
.
That's becauselanguage
/getLanguage()
in this instance returns onlyen
/fr
, without country specification.
So, I'd say, the first result (08/09/2022
) is the correct one for en_GB
. If you want a different date format you probably have to create your own one.