Ah that’s a shame. My use case is like a Todo list where items are grouped by relative date: Today, yesterday, 8 September, 10 December 2023 etc. So it would be nice if the dates were formatted in the current locale.
k
kevin.cianfarini
09/10/2024, 7:32 PM
Group them by
LocalDate
and then delegate formatting to the native platform, whether it’s Java, Apple, etc.
👍 1
m
Mark
09/11/2024, 8:36 AM
Yeah, like this:
Copy code
interface PlatformDateFormatter {
fun formatDate(date: LocalDate, includeYear: Boolean = true): String
fun formatDayOfWeek(dayOfWeek: DayOfWeek): String
}
class JavaDateFormatter(
private val locale: Locale,
): PlatformDateFormatter {
private val dateFormatWithoutYear = SimpleDateFormat("MMMM d", locale)
private val dateFormatWithYear by lazy {
SimpleDateFormat("MMMM d, yyyy", locale)
}
private val dayOfWeekFormatter = DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
.toFormatter(locale)
override fun formatDate(date: LocalDate, includeYear: Boolean): String {
return if (includeYear) {
dateFormatWithYear.format(date.millisSinceEpoch)
} else {
dateFormatWithoutYear.format(date.millisSinceEpoch)
}
}
override fun formatDayOfWeek(dayOfWeek: DayOfWeek): String {
return dayOfWeekFormatter.format(dayOfWeek)
}
}
val LocalDate.millisSinceEpoch: Long
get() = atStartOfDayIn(TimeZone.currentSystemDefault()).toEpochMilliseconds()