Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you format a kotlinx-datetime LocalDateTime?

I'm converting some code from using Java 8's LocalDatetime to using the version from kotlinx-datetime and I can't find any formatting methods. Specifically, I'm replacing a FormatStyle.MEDIUM. Do they not exist and I need to write the formatting?

This is for an Android app. Is there are there Android specific libraries I can use? Or can I do this with pre-Java 8 methods to maintain support for older versions of Android?

Edit: I posted my current solution as an answer. My requirements have changed since I asked this question. It also needs to support JVM and iOS. JS and localization are a big bonus. I'd like to see a solution that supports localization without using platform-specific code.

like image 933
Sean Avatar asked Nov 22 '25 10:11

Sean


1 Answers

Formatting is now supported by the kotlinx-datetime library:

import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.format.char

fun formatDateTime(time: LocalDateTime): String {
    val format = LocalDateTime.Format {
        year()
        char('-')
        monthNumber()
        char('-')
        dayOfMonth()

        char(' ')

        hour()
        char(':')
        minute()
        char(':')
        second()
    }

    return format.format(time)
}

If you prefer using the old-school Unicode Pattern, note that the kotlinx-datetime team prefers moving away from this:

import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.format.byUnicodePattern

@OptIn(FormatStringsInDatetimeFormats::class)
fun formatDateTime(time: LocalDateTime): String {
    val format = LocalDateTime.Format { byUnicodePattern("yyyy-MM-dd HH:mm:ss") }
    return format.format(time)
}
like image 70
Synthesis Avatar answered Nov 25 '25 04:11

Synthesis