java.util.Date to kotlinx.datetime.LocalDateTime

2.3k views Asked by At

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.

2

There are 2 answers

0
Alex Burdusel On BEST ANSWER

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
    )
  )
0
Tristan On

i Think the best thing you can do is to convert it to a string and than convert into a kotlinx.datetime.LocalDateTime

The problem is that not all java types can be converted directly into a kotlin one especially not with the old DataType java.util.Date.

It is also posible with the new DataType java.time.LocalDateTime.