I\'m new to both Java and Android development so this might be a stupid question, but I\'ve been searching for days now and can\'t find a solution:
I try to output a
getBestDateTimePattern()DateFormat.getBestDateTimePattern() from android.text.format package creates the best possible date and time according to the locale set by the user.
For example: the skeleton EEEE, MMM d, YYYY, jj:mm returns localized date and time as follows.
Locale English (India): Monday 9 Sep 2019, 9:33 PM
Locale English (United States): Monday, Sep 9, 2019, 9:33 PM
Locale español (Estados Unidos): lunes, 9 de sep. de 2019 9:33 PM
Locale español (México): lunes, 9 de sep de 2019 21:33
Locale français (France): lundi 9 sept. 2019 à 21:33
Locale português (Brasil): segunda-feira, 9 de set de 2019 21:33
and so on for different locales. It also respects the 12 hour or 24 hour time format of the locale.
For customizing your own skeleton refer to UTS #35 pattern on unicode.org.
Here's the tested sample code in Kotlin:
val skeleton = DateFormat.getBestDateTimePattern(Locale.getDefault(), "EEEE, MMM d, YYYY, jj:mm")
val formatter = SimpleDateFormat(skeleton, Locale.getDefault()).apply {
timeZone = TimeZone.getDefault()
applyLocalizedPattern(skeleton)
}
val dateTimeText = formatter.format(calendar.time)
Log.d("YourClass", "Locale ${Locale.getDefault().displayName}: $dateTimeText")
Instead of Calendar class, you can also use ZonedDateTime. Just convert it to Date object and give it to format(). For example: Date(zonedDateTime.toInstant().toEpochMilli())
Hope that helps.