LocalDateTime To Timestamp Epoch Seconds And Milliseconds

Apr 14, 2018

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

val now = LocalDateTime.now(ZoneOffset.UTC)// LocalDateTime to epoch secondsval seconds = now.atZone(ZoneOffset.UTC).toEpochSecond())// Epoch seconds to LocalDateTimeval newNow = LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneOffset.UTC)

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

// LocalDateTime to epoch millisecondsval milliseconds = now.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli()// epoch milliseconds to LocalDateTimeval 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()

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.