How to convert an Epoch to a OffsetDateTime in Kotlin?
Asked Answered
A

3

9

The postgresql Timestamp with Time Zone data type needs to be supplied an OffsetDateTime when being called using a High level language like Kotlin. I could not find a direct method that supports Epoch to OffsetDateTime conversion.

Abrade answered 3/5, 2019 at 18:35 Comment(0)
A
17
fun convertEpochToOffsetDateTime(epochValue: Long): OffsetDateTime {
  return OffsetDateTime.of(LocalDateTime.ofEpochSecond(epochValue, 0, ZoneOffset.UTC), ZoneOffset.UTC)
} 

Btw, I'm using Jooq for SQL queries using Kotlin. The above works like a charm.

Abrade answered 3/5, 2019 at 18:35 Comment(0)
A
11

Another way is to go from Long -> Instant -> OffsetDateTime

OffsetDateTime.ofInstant(Instant.ofEpochMilli(started_at), ZoneOffset.UTC)
Apollo answered 27/10, 2020 at 7:56 Comment(2)
this does not work, try converting 1613989887 which is "2021-02-22T10:31:27Z". your code will yield "1970-01-19T16:19:49.887Z"Robbie
Note the difference between seconds and milliseconds from epoc. Your value is seconds from epoc, append three zeros to it and you will get the expected answer.Apollo
A
0

Another way I just found:

fun dateFormatter(epoch: Long): String {
        // epoch = 1557954848
        val date = Date(epoch * 1000L)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
        return sdf.format(date)
        // returned value = "2019-05-15 14:14:08.000000"
}
Abrade answered 15/5, 2019 at 21:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.