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 (my solution based on the answer from Arvind):
fun Instant.toDateTimeString(formatStyle: FormatStyle = FormatStyle.MEDIUM): String {
val localDatetime = toLocalDateTime(TimeZone.currentSystemDefault())
val formatter = DateTimeFormatter.ofLocalizedDateTime(formatStyle)
return formatter.format(localDatetime.toJavaLocalDateTime())
}
As per the documentation, in a JVM, the implementation of date/time types, such as
Instant,LocalDateTime,TimeZoneand so on, relies onjava.timeAPI. It also natively supports ThreeTen backport project using which you can backport most of thejava.timefunctionality to Java 6 & 7. Check How to use ThreeTenABP in Android Project to learn how to set it up.In case you want to replace an OOTB (Out-Of-The-Box) format e.g
FormatStyle.MEDIUM, you can always define a custom format usingDateTimeFormattere.g.Output:
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for
java.time. Check this answer and this answer to learn how to usejava.timeAPI with JDBC.