0

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);
Ahsan Malik
  • 57
  • 1
  • 4
  • 10
  • 1
    Consider not using `SimpleDateFormat` and related classes since `SImpleDateFormat` is notoriously troublesome and long outdated. I suggest java.time, the modern Java date and time API. Built-in since API level 26 and available for lower levels through desugaring. See the answer by Nitesh. – Ole V.V. Nov 22 '21 at 21:50

2 Answers2

7

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: ٣ نوفمبر, ٢٠٢١

Nitish
  • 3,075
  • 3
  • 13
  • 28
2

The date language is determined by the system language, but to display the date in specific languages ​​without relying on the system language. You can do like this

 TextView arabicText = findViewById(R.id.arabic);
 TextView englishText = findViewById(R.id.english);
    
 Date date = new Date();
    
 SimpleDateFormat arDate = new SimpleDateFormat("d MMM yyyy", new Locale("ar"));
 SimpleDateFormat enDate = new SimpleDateFormat("d MMM yyyy", new Locale("en"));
    
 String ar = arDate.format(date);
 String en = enDate.format(date);
    
    
 arabicText.setText(ar);
 englishText.setText(en);
droid24
  • 124
  • 6