7

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.

Raj
  • 3,637
  • 8
  • 29
  • 52

3 Answers3

15
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.

Raj
  • 3,637
  • 8
  • 29
  • 52
9

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

OffsetDateTime.ofInstant(Instant.ofEpochMilli(started_at), ZoneOffset.UTC)
34m0
  • 5,755
  • 1
  • 30
  • 22
  • this does not work, try converting 1613989887 which is "2021-02-22T10:31:27Z". your code will yield "1970-01-19T16:19:49.887Z" – Uri Loya Feb 22 '21 at 10:33
  • 1
    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. – 34m0 Feb 22 '21 at 12:16
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"
}
Raj
  • 3,637
  • 8
  • 29
  • 52