LocalDateTime To Timestamp Epoch Seconds And Milliseconds

October 4, 2019

Convert LocalDateTime to seconds since January 1, 1970, 00:00:00 GMT

val now = LocalDateTime.now(ZoneOffset.UTC)

// LocalDateTime to epoch seconds
val seconds = now.atZone(ZoneOffset.UTC).toEpochSecond())

// Epoch seconds to LocalDateTime
val newNow = LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneOffset.UTC)

Convert LocalDateTime to milliseconds since January 1, 1970, 00:00:00 GMT

// LocalDateTime to epoch milliseconds
val milliseconds = now.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli()

// epoch milliseconds to LocalDateTime
val newNow = LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneOffset.UTC)

NOTE: Timestamp Epoch to LocalDateTime / Java8 Date Time.

Kotlin Extensions

fun LocalDateTime.toMillis(zone: ZoneId = ZoneId.systemDefault()) = atZone(zone)?.toInstant()?.toEpochMilli()
val now = LocalDateTime.now()
val millis = now.toMillis()
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.