It cannot be done a lot easier. Two suggestions for simplifications:
- Use java.time, the modern Java date and time API. In this case we substitute two old classes,
Calendar
and Date
, with just one new class, LocalDate
. So it saves us a conversion. Also the classes you used are long outdated, and generally java.time is much nicer to work with.
- Use the built-in localized date format for the user’s locale rather than writing a format pattern string. The latter tends to be error-prone, and using the built-in format lends itself much better to internationalization.
The code below is not tested, there’s probably a typo or two, but you should get the idea.
val date = LocalDate.now(ZoneId.of("Africa/Abidjan"))
val currentYear = date.year
val currentMonth = date.monthValue
val currentDay = date.dayOfMonth
val dateFormatter = DateTimeFormatter.ofLocalizedDate(TextStyle.MEDIUM)
pickDate.setOnClickListener {
val datePickDialog = DatePickerDialog(
activity,
DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
val selectedDate = LocalDate.of(year, month + 1, dayOfMonth)
val dateString = selectedDate.format(dateFormatter)
currentDateView.text = dateString
},
currentYear,
currentMonth - 1,
currentDay
)
datePickDialog.show()
}
Insert your desired time zone where I put Africa/Abidjan. Use ZoneId.systemDefault
for the default time zone (this is what the code in your question used). I have also taken the formatter out of the event listener. There’s no need to construct a new formatter each time.
Question: Can I use java.time on Android? I in project use min API 21
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links