Unix Timestamp in Kotlin

Kotlin on the JVM uses java.time; multiplatform code uses kotlinx-datetime, which wraps the same concepts.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

import java.time.Instant

System.currentTimeMillis()               // 1710050400000
Instant.now().epochSecond                // 1710050400

Timestamp to date

import java.time.*
import java.time.format.DateTimeFormatter

val instant = Instant.ofEpochSecond(1710050400)
val zoned = instant.atZone(ZoneId.of("Asia/Kolkata"))

println(zoned.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z")))

Date to timestamp

val zdt = ZonedDateTime.of(
    LocalDateTime.of(2024, 3, 10, 11, 30, 0),
    ZoneId.of("Asia/Kolkata"))

println(zdt.toEpochSecond())             // 1710050400

kotlinx-datetime (multiplatform)

import kotlinx.datetime.*

val now: Instant = Clock.System.now()
println(now.epochSeconds)

val tz = TimeZone.of("Asia/Kolkata")
println(Instant.fromEpochSeconds(1710050400).toLocalDateTime(tz))

Pitfalls specific to Kotlin

  • On Android, java.time needs API 26+ or core library desugaring enabled in Gradle.
  • kotlinx-datetime's Instant and java.time's Instant are different types with the same name — watch your imports.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in Kotlin?

Use the snippet in the "Current Unix timestamp" section above. Kotlin works in integer milliseconds natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in Kotlin?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does Kotlin handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways Kotlin makes that easy to get wrong.