now
Returns the Instant corresponding to the current time, according to this clock.
Calling now later is not guaranteed to return a larger Instant. In particular, for Clock.System, the opposite is completely expected, and it must be taken into account. See the System documentation for details.
Even though Instant is defined to be on the UTC-SLS time scale, which enforces a specific way of handling leap seconds, now is not guaranteed to handle leap seconds in any specific way.
Note that while Instant supports nanosecond precision, the actual precision of the returned Instant depends on the resolution of the Clock implementation.
Since Kotlin
2.1Samples
import kotlin.time.*
fun main() {
//sampleStart
// The current instant according to the system clock.
val currentInstant = Clock.System.now()
// The number of whole milliseconds that have passed since the Unix epoch.
println(currentInstant.toEpochMilliseconds())
//sampleEnd
}
import kotlin.time.*
fun main() {
//sampleStart
fun formatCurrentTime(clock: Clock): String =
clock.now().toString()
// In the production code:
val currentTimeInProduction = formatCurrentTime(Clock.System)
// Testing this value is tricky because it changes all the time.
println(currentTimeInProduction)
// In the test code:
val testClock = object : Clock {
override fun now(): Instant = Instant.parse("2023-01-02T22:35:01Z")
}
// Then, one can write a completely deterministic test:
val currentTimeForTests = formatCurrentTime(testClock)
println(currentTimeForTests) // 2023-01-02T22:35:01Z
//sampleEnd
}