paug / AndroidMakersApp

📱Official companion app for Android Makers by droidcon 🇫🇷
https://androidmakers.droidcon.com/
117 stars 27 forks source link

Optimize Android date and time formatting #315

Closed cbeyls closed 3 weeks ago

cbeyls commented 3 weeks ago

The current Android code uses the legacy java.text.SimpleDateFormat class and creates a new instance of it for every formatting. This also requires unnecessary conversion of the date or time to the legacy Date first.

This pull request uses the new thread-safe DateTimeFormatter to format LocalDate and LocalTime, the classes used internally by the kotlinx datetime types. Unwrapping the internal value is a free operation. In addition, cache the DateTimeFormatter for the current Locale using a thread-safe custom memoization function. The cache will be invalidated when the default locale changes so the dates will always be localized properly.

Note that DateTimeFormatter and other java.time APIs are available before API 26 thanks to core library desugaring being enabled in the Android app configuration.

Finally, upgrade the kotlinx datetime library to 0.6.0.