Search code examples
javaandroidkotlindateandroid-version

Date Format issue in Android 12 & 13


I am using dd-MMM-yyyy format in String format in kotlin in android.
It returns "01-Sept-2022" as a result.
I want "01-Sep-2022" as result.
This issue shows up in android 12 & 13.

@JvmStatic
fun getCurrentDate(format: String): String {
    val sdf = SimpleDateFormat(format)
    val currentDate = sdf.format(Date())
    return currentDate
}

How can I get my desired return value in all versions?


Solution

  • According to @deHaar SimpleDateFormat returns the formatted string depending on the Locale. Take a look at all locales and you will find the correct form you want. Below I added a snippet where you can easily find it. If you develop this app for the app store or for other public users you shouldn't change the Locale in SimpleDateFormat because the user in this region normally knows this format. The Locale.getDefault is also influenced by the Android system settings.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
        val out = findViewById<TextView>(R.id.out)
        out.text = getCurrentDate("dd-MMM-yyyy")
    }
    
    fun getCurrentDate(format: String): String {
        var result = ""
    
        val locales = listOf<Locale>(Locale.CANADA, Locale.CANADA_FRENCH, Locale.CHINA, Locale.CHINESE,
            Locale.ENGLISH, Locale.FRANCE, Locale.FRENCH, Locale.GERMAN, Locale.GERMANY, Locale.ITALIAN,
            Locale.ITALY, Locale.JAPAN, Locale.JAPANESE, Locale.KOREA, Locale.KOREAN, Locale.PRC,
            Locale.ROOT, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE, Locale.UK, Locale.US)
    
        locales.forEach {
            val sdf = SimpleDateFormat(format, it)
            result += sdf.format(Date()) + "\n"
        }
        return result
    }
    

    returns

    04-Sep.-2022
    04-sept.-2022
    04-9月-2022
    04-9月-2022
    04-Sep-2022
    04-sept.-2022
    04-sept.-2022
    04-Sept.-2022
    04-Sept.-2022
    04-set-2022
    04-set-2022
    04-9月-2022
    04-9月-2022
    04-9월-2022
    04-9월-2022
    04-9月-2022
    04-Sep-2022
    04-9月-2022
    04-9月-2022
    04-9月-2022
    04-Sep-2022
    04-Sep-2022