System

object System : Clock(source)

The Clock instance that queries the platform-specific system clock as its source of time knowledge.

Successive calls to now will not necessarily return increasing Instant values, and when they do, these increases will not necessarily correspond to the elapsed time.

For example, when using Clock.System, the following could happen:

  • now returns 2023-01-02T22:35:01Z.

  • The system queries the Internet and recognizes that its clock needs adjusting.

  • now returns 2023-01-02T22:32:05Z.

When you need predictable intervals between successive measurements, consider using TimeSource.Monotonic.

For improved testability, you should avoid using Clock.System directly in the implementation and pass a Clock explicitly instead. For example:

Samples

import kotlinx.datetime.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   // Getting the current date and time
val zone = TimeZone.of("Europe/Berlin")
val currentInstant = Clock.System.now()
val currentLocalDateTime = currentInstant.toLocalDateTime(zone)
currentLocalDateTime.toString() // show the current date and time, according to the OS 
   //sampleEnd
}
import kotlinx.datetime.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   fun formatCurrentTime(clock: Clock, timeZone: TimeZone): String =
    clock.now().toLocalDateTime(timeZone).toString()

// In the production code:
val currentTimeInProduction = formatCurrentTime(Clock.System, TimeZone.currentSystemDefault())
// Testing this value is tricky because it changes all the time.

// 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, TimeZone.of("Europe/Paris"))
check(currentTimeForTests == "2023-01-02T23:35:01") 
   //sampleEnd
}

Functions

Link copied to clipboard
open override fun now(): Instant

Returns the Instant corresponding to the current time, according to this clock.