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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With