Instant and Clock in kotlin.time

suggest change

An Instant is a point on the timeline: a number of seconds and nanoseconds since 1970-01-01T00:00:00Z. It has no time zone and no calendar. It's what you want for timestamps in logs, createdAt columns, token expiry times and API payloads.

For a long time Kotlin code got this type from java.time.Instant (JVM only) or kotlinx.datetime.Instant (multiplatform, separate library). Now the standard library has its own kotlin.time.Instant, plus kotlin.time.Clock to read the current time. They work the same on JVM, JS, Wasm and Native, so common code can handle timestamps without java.time and without extra dependencies.

Versions:

All the examples below were compiled and run with Kotlin 2.4.21 on JDK 25. If you're still on 2.1.20 to 2.2.x, add @OptIn(ExperimentalTime::class) (see Opt-in requirements). With a 2.3+ compiler the annotation is harmless, so you can leave it in place while you upgrade.

This article covers the standard library types. For calendar dates, time zones and the rest of java.time, see Dates and time.

Getting the current time

Clock.System.now() returns the current time from the system clock:

import kotlin.time.Clock
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant

fun main() {
    val now: Instant = Clock.System.now()
    println(now)

    val start = Instant.parse("2024-03-15T13:00:00Z")
    val end = start + 2.hours + 30.seconds
    println(end)
    println(start - 1.days)

    val elapsed = end - start   // Instant - Instant = Duration
    println(elapsed)
    println(elapsed.inWholeSeconds)

    println(start < end)
    println(start == Instant.parse("2024-03-15T15:00:00+02:00"))
    println(maxOf(start, end))
    println(Instant.parse("2024-03-15T14:00:00Z") in start..end)
}

Output (the first line changes on every run):

2026-10-17T23:02:10.406242400Z
2024-03-15T15:00:30Z
2024-03-14T13:00:00Z
2h 0m 30s
7230
true
true
2024-03-15T15:00:30Z
true

What this shows:

The precision of now() depends on the platform. On the JVM it comes from java.time.Clock.systemUTC(), which gives microseconds or better (the example above shows 100 ns ticks on Windows). On JS it's milliseconds.

There's no Instant.now(). It exists only as a deprecated function that fails to compile with "Use Clock.System.now() instead". The deprecation is there on purpose: reading the time through a Clock makes it easy to swap the clock in tests (see below).

Don't use Instant to measure elapsed time

Clock.System follows the wall clock, which can jump backwards or forwards when NTP or a user changes it. To measure how long something took, use the monotonic TimeSource.Monotonic, measureTime or measureTimedValue instead. Benchmarks shows how. Use Instant for "when did this happen", and TimeSource for "how long did it take".

Epoch seconds and milliseconds

Inside, an Instant is a Long count of seconds plus an Int of nanoseconds. Databases, JWTs, Unix tools and JavaScript use epoch seconds or milliseconds, so you'll convert often:

import kotlin.time.Clock
import kotlin.time.Instant

fun main() {
    val i = Instant.parse("2024-03-15T13:00:00.123456789Z")
    println(i.epochSeconds)            // whole seconds since 1970-01-01T00:00:00Z
    println(i.nanosecondsOfSecond)     // 0..999_999_999
    println(i.toEpochMilliseconds())   // truncated to milliseconds

    println(Instant.fromEpochSeconds(1_700_000_000))
    println(Instant.fromEpochSeconds(1_700_000_000, 250_000_000))
    println(Instant.fromEpochMilliseconds(1_700_000_000_250))

    // nanosecond adjustment can be out of range; it's normalized
    println(Instant.fromEpochSeconds(10, -1))
    println(Instant.fromEpochSeconds(10, 1_500_000_000L))

    // before 1970: negative seconds, nanos still positive
    val old = Instant.parse("1969-12-31T23:59:59.5Z")
    println("${old.epochSeconds} ${old.nanosecondsOfSecond} ${old.toEpochMilliseconds()}")

    // like System.currentTimeMillis()
    val millis = Clock.System.now().toEpochMilliseconds()
    println(millis > 1_700_000_000_000)
}

Output:

1710507600
123456789
1710507600123
2023-11-14T22:13:20Z
2023-11-14T22:13:20.250Z
2023-11-14T22:13:20.250Z
1970-01-01T00:00:09.999999999Z
1970-01-01T00:00:11.500Z
-1 500000000 -500
true

The standard library has no truncation function. To drop the fraction, or round down to the hour, go through epoch seconds:

val i = Instant.parse("2024-03-15T13:45:12.987Z")
println(Instant.fromEpochSeconds(i.epochSeconds))               // 2024-03-15T13:45:12Z
println(Instant.fromEpochSeconds(i.epochSeconds / 3600 * 3600)) // 2024-03-15T13:00:00Z

Rounding to an hour or minute only works this way in UTC. Rounding to a day boundary needs a time zone, so use kotlinx-datetime or java.time for that.

Range and DISTANT_PAST / DISTANT_FUTURE

Instant supports a very large range, and arithmetic that goes past it is clamped, not wrapped around. Instant.DISTANT_PAST and Instant.DISTANT_FUTURE are useful as "no limit" values:

import kotlin.time.Duration.Companion.days
import kotlin.time.Instant
import kotlin.time.isDistantFuture

data class Coupon(val code: String, val validUntil: Instant = Instant.DISTANT_FUTURE)

fun main() {
    println(Instant.DISTANT_PAST)
    println(Instant.DISTANT_FUTURE)

    val c = Coupon("WELCOME")
    println(c.validUntil.isDistantFuture)
    println(c.validUntil + 365.days)   // no overflow

    // values outside the supported range are clamped, not wrapped
    println(Instant.fromEpochSeconds(Long.MAX_VALUE))
    println(Instant.fromEpochMilliseconds(Long.MIN_VALUE))
}

Output:

-100001-12-31T23:59:59.999999999Z
+100000-01-01T00:00:00Z
true
+100000-12-31T00:00:00Z
+1000000000-12-31T23:59:59.999999999Z
-292275055-05-16T16:47:04.192Z

isDistantPast and isDistantFuture are extension properties, so they need their own imports (kotlin.time.isDistantPast, kotlin.time.isDistantFuture). They return true for anything at or beyond those values.

Parsing and formatting ISO 8601

Instant.parse() accepts the ISO 8601 date-time format with a UTC offset, and toString() produces it:

import kotlin.time.Instant

fun main() {
    println(Instant.parse("2024-03-15T13:00:00Z"))
    println(Instant.parse("2024-03-15T15:00:00+02:00"))   // offset is applied, result is UTC
    println(Instant.parse("2024-03-15T13:00:00.5Z"))      // fraction printed in groups of 3
    println(Instant.parse("2024-03-15T13:00:00.1234Z"))
    println(Instant.parse("2024-03-15T13:00:00.000Z"))    // zero fraction is dropped
    println(Instant.parse("+12024-03-15T13:00:00Z"))      // years past 9999 need a sign

    for (s in listOf("2024-03-15 13:00:00Z", "2024-03-15T13:00:00", "2024-03-15T13:00Z", "2024-02-30T00:00:00Z")) {
        println("$s -> ${Instant.parseOrNull(s)}")
    }

    try {
        Instant.parse("2024-03-15T13:00:00")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}

Output:

2024-03-15T13:00:00Z
2024-03-15T13:00:00Z
2024-03-15T13:00:00.500Z
2024-03-15T13:00:00.123400Z
2024-03-15T13:00:00Z
+12024-03-15T13:00:00Z
2024-03-15 13:00:00Z -> null
2024-03-15T13:00:00 -> null
2024-03-15T13:00Z -> null
2024-02-30T00:00:00Z -> null
The input string is too short when parsing an Instant from "2024-03-15T13:00:00" when parsing an Instant from "2024-03-15T13:00:00"

The rules:

For any other format, such as an HTTP Date header, a custom log format or a local time in a time zone, use kotlinx-datetime (below) or convert to java.time.Instant on the JVM.

Converting to and from java.time

On the JVM, kotlin.time.Instant converts to and from java.time.Instant without losing precision. kotlin.time.Duration and java.time.Duration convert too:

import java.time.ZoneId
import java.util.Date
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant
import kotlin.time.toJavaDuration
import kotlin.time.toJavaInstant
import kotlin.time.toKotlinDuration
import kotlin.time.toKotlinInstant

fun main() {
    val k = Instant.parse("2024-03-15T13:00:00.123456789Z")

    val j: java.time.Instant = k.toJavaInstant()
    println(j)
    println(j.atZone(ZoneId.of("America/New_York")))

    val back: Instant = j.plusSeconds(60).toKotlinInstant()
    println(back)
    println(back - k)

    // legacy java.util.Date via java.time
    val date: Date = Date.from(k.toJavaInstant())
    println(date.time)
    println(date.toInstant().toKotlinInstant())

    // Durations convert too
    println(15.minutes.toJavaDuration())
    println(java.time.Duration.ofSeconds(90).toKotlinDuration())
}

Output:

2024-03-15T13:00:00.123456789Z
2024-03-15T09:00:00.123456789-04:00[America/New_York]
2024-03-15T13:01:00.123456789Z
1m
1710507600123
2024-03-15T13:00:00.123Z
PT15M
1m 30s

The two Instant types have the same name, so in a file that uses both, import one and write the other fully qualified, as above, or use an import alias (import java.time.Instant as JavaInstant).

Where to convert: keep kotlin.time.Instant in your domain code and convert at the edges, where a library wants java.time: JDBC (java.sql.Timestamp.from(i.toJavaInstant())), Jackson, java.time.format.DateTimeFormatter, and older Java APIs that use Date. java.util.Date only has millisecond precision, so the nanoseconds are lost on that path.

Injecting a Clock for tests

Clock is an interface with one method, now(). Code that takes a Clock parameter instead of calling Clock.System.now() directly can be tested without waiting or mocking statics:

import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant

class Session(val user: String, val expiresAt: Instant)

class SessionStore(
    private val ttl: Duration = 30.minutes,
    private val clock: Clock = Clock.System,
) {
    private val sessions = mutableMapOf<String, Session>()

    fun login(token: String, user: String) {
        sessions[token] = Session(user, clock.now() + ttl)
    }

    fun userFor(token: String): String? {
        val s = sessions[token] ?: return null
        if (clock.now() >= s.expiresAt) {
            sessions.remove(token)
            return null
        }
        return s.user
    }
}

class FakeClock(var current: Instant) : Clock {
    override fun now(): Instant = current
    fun advance(d: Duration) { current += d }
}

fun main() {
    val clock = FakeClock(Instant.parse("2024-03-15T10:00:00Z"))
    val store = SessionStore(clock = clock)
    store.login("t1", "alice")

    clock.advance(29.minutes)
    println("after 29m: ${store.userFor("t1")}")

    clock.advance(1.minutes)
    println("after 30m: ${store.userFor("t1")}")
}

Output:

after 29m: alice
after 30m: null

Production code uses the default Clock.System, and the test passes a FakeClock and moves it forward to exactly the moment it cares about. The test is fast and gives the same result on every run. The same pattern works for caching (entry expiry), rate limiting and scheduled jobs.

You don't have to write FakeClock yourself. The standard library's TestTimeSource is a fake monotonic clock you advance by hand, and asClock(origin) turns any TimeSource into a Clock that starts at the given instant:

import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.time.TestTimeSource
import kotlin.time.Duration.Companion.minutes
import kotlin.time.asClock

fun main() {
    val time = TestTimeSource()
    val clock: Clock = time.asClock(origin = Instant.parse("2024-03-15T10:00:00Z"))
    println(clock.now())
    time += 90.minutes
    println(clock.now())
}

Output:

2024-03-15T10:00:00Z
2024-03-15T11:30:00Z

If the code under test uses both a TimeSource (to measure durations) and a Clock (for timestamps), give it a clock made from the same TestTimeSource, and advancing it moves both.

Bridging from java.time.Clock

JVM code that already passes a java.time.Clock around (as in Dates and time) can wrap it, since the standard library has no built-in conversion:

import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.time.toKotlinInstant

class JavaClockAdapter(private val javaClock: java.time.Clock) : Clock {
    override fun now(): Instant = javaClock.instant().toKotlinInstant()
}

fun main() {
    val fixed = java.time.Clock.fixed(java.time.Instant.parse("2024-01-01T00:00:00Z"), java.time.ZoneOffset.UTC)
    val clock: Clock = JavaClockAdapter(fixed)
    println(clock.now())
}

Output:

2024-01-01T00:00:00Z

kotlinx-datetime: time zones and formats on top

The standard library deliberately stops at Instant and Clock. Anything involving a calendar or a time zone, such as "what date is it in Tokyo", "add one month" or "format as an HTTP date", lives in kotlinx-datetime:

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.8.0")
}

Since version 0.7.0 that library has no Instant or Clock of its own. Its functions take and return kotlin.time.Instant and kotlin.time.Clock, so values move between them with no conversion:

import kotlin.time.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.UtcOffset
import kotlinx.datetime.format
import kotlinx.datetime.format.DateTimeComponents
import kotlinx.datetime.format.char
import kotlinx.datetime.offsetIn
import kotlinx.datetime.parse
import kotlinx.datetime.toLocalDateTime

fun main() {
    val i = Instant.parse("2024-03-15T13:00:00Z")

    // ISO 8601 with a fixed offset instead of Z
    println(i.format(DateTimeComponents.Formats.ISO_DATE_TIME_OFFSET, UtcOffset(hours = 2)))

    // HTTP date header
    val header = i.format(DateTimeComponents.Formats.RFC_1123)
    println(header)
    println(Instant.parse(header, DateTimeComponents.Formats.RFC_1123))

    // custom format
    val logFormat = DateTimeComponents.Format {
        year(); char('/'); monthNumber(); char('/'); day()
        char(' ')
        hour(); char(':'); minute(); char(':'); second()
    }
    println(i.format(logFormat))
    val warsaw = TimeZone.of("Europe/Warsaw")
    println(i.format(logFormat, i.offsetIn(warsaw)))
    println(i.toLocalDateTime(warsaw))
}

Output:

2024-03-15T15:00:00+02:00
Fri, 15 Mar 2024 13:00:00 GMT
2024-03-15T13:00:00Z
2024/03/15 13:00:00
2024/03/15 14:00:00
2024-03-15T14:00

The format extension on Instant and the two-argument Instant.parse(input, format) come from the kotlinx.datetime package, so they need explicit imports when you don't use import kotlinx.datetime.*. kotlinx-datetime also adds Clock.todayIn(timeZone) and calendar arithmetic such as instant.plus(1, DateTimeUnit.MONTH, timeZone).

Current kotlinx.serialization (tested with 1.11.0) has a built-in serializer for kotlin.time.Instant, so it works in @Serializable classes with no extra setup and is written as an ISO 8601 string, for example {"name":"deploy","at":"2024-03-15T13:00:00.500Z"}. See JSON for more on kotlinx.serialization.

Migrating from kotlinx.datetime.Instant

Code written for kotlinx-datetime 0.6 and earlier imports kotlinx.datetime.Instant and kotlinx.datetime.Clock. In 0.7 and later:

Common code without java.time

Because Instant and Clock are in the standard library, Kotlin Multiplatform code in commonMain can store timestamps, compare them, compute expirations and serialize them as ISO 8601 or epoch milliseconds, with no expect/actual and no dependency. Add kotlinx-datetime only when you need local dates and time zones. Together with kotlin.uuid.Uuid (see UUIDs) and kotlin.io.encoding.Base64, that covers most of what a typical data model needed java.time and java.util for.

Summary

Task Code
current time Clock.System.now()
parse ISO 8601 Instant.parse(s) / Instant.parseOrNull(s)
format ISO 8601 (UTC) instant.toString()
add or subtract time instant + 5.minutes, instant - 1.days
time between two instants end - start (a Duration)
epoch seconds instant.epochSeconds / Instant.fromEpochSeconds(s, nanos)
epoch milliseconds instant.toEpochMilliseconds() / Instant.fromEpochMilliseconds(ms)
"no limit" values Instant.DISTANT_PAST, Instant.DISTANT_FUTURE
java.time interop (JVM) instant.toJavaInstant() / javaInstant.toKotlinInstant()
fake clock in tests implement Clock, or TestTimeSource().asClock(origin)
time zones, custom formats kotlinx-datetime 0.7+
measure elapsed time TimeSource.Monotonic / measureTime, not Instant

Store and pass around Instant, read it from an injected Clock, and convert to a time zone only when showing a value to a person.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents