Home > database >  How to show date format in both english and arabic?
How to show date format in both english and arabic?

Time:11-23

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);

CodePudding user response:

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);

CodePudding user response:

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

  • Related