Search code examples
androiddatedatetimesimpledateformatarabic

How to show date format in both english and arabic?


Hi I want to achieve format of date like this "2021 نوفمبر" can anybody help me how I can achieve this format?

Here is my sample source code

 SimpleDateFormat dateFormatter = new SimpleDateFormat("d MMM yyyy", locale);
            dateString = dateFormatter.format(date);

Solution

  • Setting the Locale to "ar" will convert the date format from English to Arabic.
    I have also used DateTimeFormatter , as SimpleDateFormat is outdated

    fun parseDate() {
        var formatter: DateTimeFormatter? = null
        val date = "2021-11-03T14:09:31"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
            val dateTime: LocalDateTime = LocalDateTime.parse(date, formatter)
            val formatter2: DateTimeFormatter =
                DateTimeFormatter.ofPattern(
                    "yyyy, MMM d", Locale("ar")  // set the language in which you want to convert
                                                // For english use Locale.ENGLISH
                )
            Log.e("Date", "" + dateTime.format(formatter2))
        }
    }
    

    Note: DateTimeFormatter only works in android 8 and above, to use it below android 8 enable desugaring

    Output : 2021, نوفمبر 3

    Edit: : If you want to convert numbers also to arabic use withDecimalStyle with the DateTimeFormatter.

     val formatter2: DateTimeFormatter =
                    DateTimeFormatter.ofPattern(
                        "d MMM, yyyy",
                        Locale("ar")
                    ).withDecimalStyle(
                        DecimalStyle.of(Locale("ar"))
                    )
    

    Output: ٣ نوفمبر, ٢٠٢١