I have a value of type java.util.Date
which was obtained from a legacy third-party API. Is there a direct way of converting it to kotlinx.datetime.LocalDateTime
? I know how to do it only in a roundabout way, such as serializing to String and deserializing, or by converting to java.time.LocalDateTime
first and then to the wanted type.
I think the most efficient conversion would be with Instant.fromEpochMilliseconds
Here's an example extension. You can do something similar for other types that you may need
import java.util.Date
import kotlinx.datetime.FixedOffsetTimeZone
import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.UtcOffset
import kotlinx.datetime.toLocalDateTime
fun Date.toLocalDateTime(): LocalDateTime =
Instant.fromEpochMilliseconds(this.time).toLocalDateTime(
FixedOffsetTimeZone(
UtcOffset.ZERO
)
)