Unix timestamps in Kotlin

Get the current epoch time and convert between timestamps and dates in Kotlin. Every snippet below is copy-ready.

// note

java.time works on the JVM; kotlinx-datetime for multiplatform.

Now.kt · current timestamp
val nowSeconds = System.currentTimeMillis() / 1000
val nowMillis  = System.currentTimeMillis()
timestamp → date
val ts = 1_700_000_000L
val instant = Instant.ofEpochSecond(ts)
println(instant) // 2023-11-14T22:13:20Z
date → timestamp
val ts = Instant.parse("2023-11-14T22:13:20Z").epochSecond
// current epoch

— seconds since 1970-01-01T00:00:00Z.

Watch out for these

  • Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
  • Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
  • Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.

Reference: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.time/

advertisement