DateTimeFormatter does not use Arabic or Bengali native numbers… here is a solution to the problem.
DateTimeFormatter does not use Arabic or Bengali native numbers
I’m trying to display a specific time in a TextView
using the DateTimeFormatter
API, but whenever I run my app my device is set to Arabic or Bengali, somehow the time always seems to show Western numerals. Is this intentional, or is there something I need to do to fix this?
Kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val localizedTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
val timeOpen = LocalTime.of(9, 30)
val timeClose = LocalTime.of(17, 15)
tv_time.text = (timeOpen.format(localizedTimeFormatter) +
"\n\n" + timeClose.format(localizedTimeFormatter))
}
}
Clock app (Arabic).
My app (Arabic).
Clock app (Bengali).
My app (Bengali).
Solution
This is by design. DateTimeFormatter's
instances, even localized ones, use Western/ASCII numerals unless explicitly stated otherwise. The instructions are not difficult when you know how to do it:
DateTimeFormatter localizedTimeFormatter = DateTimeFormatter
.ofLocalizedTime(FormatStyle.SHORT)
.withDecimalStyle(DecimalStyle.ofDefaultLocale());
LocalTime timeOpen = LocalTime.of(9, 30);
LocalTime timeClose = LocalTime.of(17, 15);
String text = timeOpen.format(localizedTimeFormatter)
+ '\n' + timeClose.format(localizedTimeFormatter);
System.out.println(text);
Output of the Bengali locale (bn-BD):
৯:৩০ AM ৫:১৫ PM
Arabic (ar):
٩:٣٠ ص ٥:١٥ م
I hope you can translate my Java code yourself. I believe it shouldn’t be difficult.