now
Начиная с Kotlin: 2.3
abstract fun now(): Instant
Возвращает Instant, соответствующий текущему времени согласно этим часам.
Вызов now позднее не гарантирует возврат большего значения Instant. В частности, для Clock.System ожидается прямо противоположное, и это необходимо учитывать. Подробнее см. в документации System.
Несмотря на то, что для Instant определена шкала времени UTC-SLS, задающая определённый способ обработки високосных секунд, для now не гарантируется какой-либо конкретный способ обработки високосных секунд.
Обратите внимание: хотя Instant поддерживает наносекундную точность, фактическая точность возвращаемого значения Instant зависит от разрешения реализации Clock.
Примеры
import kotlin.time.*
import kotlin.time.Duration.Companion.seconds
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.*
import kotlin.time.Duration.Companion.seconds
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
}
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.time/-clock/now.html