Handling Android Locale

Issue

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?

Solution

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.

Answered By – Gowtham K K

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published