Is there a way to format a `LocalDate` without sho...
# kotlinx-datetime
m
Is there a way to format a
LocalDate
without showing the year? Equivalent of Android’s
DateUtils.FORMAT_NO_YEAR
d
Copy code
LocalDate.Format {
  monthNumber(); char('-'); dayOfMonth()
}.format(LocalDate(2024, 5, 6))
m
Thanks, but I was hoping for something that would output a format like “10 September” but also according to current Locale
d
There's unfortunately no such thing at the moment: https://github.com/Kotlin/kotlinx-datetime/issues/352
m
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
Group them by
LocalDate
and then delegate formatting to the native platform, whether it’s Java, Apple, etc.
👍 1
m
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()