Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Android date and time formatting #315

Merged
merged 4 commits into from
May 27, 2024

Conversation

cbeyls
Copy link
Contributor

@cbeyls cbeyls commented May 26, 2024

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.

@martinbonnin martinbonnin merged commit d4b4eaf into paug:main May 27, 2024
1 check passed
}

actual fun LocalDate.formatMediumDate(): String {
val dateFormat = SimpleDateFormat.getDateInstance(MEDIUM)

val tz = TimeZone.getTimeZone("Europe/Paris")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also note that the previous code may produce incorrect output because the LocalDate is transformed to a Date using the system default timezone but then formatted using the Paris timezone which may be different.
So if the Paris timezone is at the west of the current timezone, the previous day will be shown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants