androidkotlindatetimetimezone

Getting ISO 8601 datetime string from Instant on Android


I have a time represented in a Kotlin Instant. I want to obtain the ISO 8601 datetime string for the local timezone on Android. But I'm running into conflicts with two separate classes called TimeZone, and don't know how to translate between them (or if I'm on the right path at all).

The Kotlin docs say to use Instant.toLocalDateTime() and pass it a TimeZone. That's androidx.datetime.TimeZone.

They Android docs say to obtain the local Timezone using TimeZone.getDefault(). But that's android.icu.util.TimeZone.

What's the proper way to accomplish this simple task?


Solution

  • There are several different date frameworks available with limited interoperability.

    You chose to use the Kotlin datetime library from the kotlinx.datetime package so far, so the easiest way would be to keep using it. toLocalDateTime requires a parameter of type kotlinx.datetime.TimeZone, so you can use TimeZone.currentSystemDefault() to get the current timezone when you use

    import kotlinx.datetime.TimeZone
    

    Do not use any of these:

    import android.icu.util.TimeZone
    import java.util.TimeZone