asClock

Creates a Clock that uses the TimeMark.markNow to determine how far the current moment is from the origin.

This clock stores the TimeMark at the moment of creation, so repeatedly creating Clocks from the same TimeSource results in different Instants iff the time of the TimeSource was increased. To sync different Clocks, use the origin parameter.

Samples

import kotlinx.datetime.*
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TestTimeSource

fun main() { 
   //sampleStart 
   // Creating a TimeSource
// When testing a Clock in combination of kotlinx-coroutines-test, use the testTimeSource of the TestDispatcher.
val timeSource = TestTimeSource()
// Creating a clock by setting the origin, here the epoch start
val clock = timeSource.asClock(origin = Instant.fromEpochSeconds(0))

check(Instant.fromEpochSeconds(0) == clock.now())

// Increasing the timeSource
timeSource += 1.seconds
check(Instant.fromEpochSeconds(1) == clock.now()) 
   //sampleEnd
}