|
| 1 | +/* |
| 2 | + * Copyright 2019-2020 JetBrains s.r.o. |
| 3 | + * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. |
| 4 | + */ |
| 5 | + |
| 6 | +package kotlinx.datetime |
| 7 | + |
| 8 | +import kotlin.time.* |
| 9 | + |
| 10 | +/** |
| 11 | + * A source of [Instant] values. |
| 12 | + * |
| 13 | + * See [Clock.System][Clock.System] for the clock instance that queries the operating system. |
| 14 | + */ |
| 15 | +public interface Clock { |
| 16 | + /** |
| 17 | + * Returns the [Instant] corresponding to the current time, according to this clock. |
| 18 | + */ |
| 19 | + public fun now(): Instant |
| 20 | + |
| 21 | + /** |
| 22 | + * The [Clock] instance that queries the operating system as its source of knowledge of time. |
| 23 | + */ |
| 24 | + public object System : Clock { |
| 25 | + override fun now(): Instant = @Suppress("DEPRECATION_ERROR") Instant.now() |
| 26 | + } |
| 27 | + |
| 28 | + public companion object { |
| 29 | + |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Returns the current date at the given [time zone][timeZone], according to [this Clock][this]. |
| 35 | + */ |
| 36 | +public fun Clock.todayIn(timeZone: TimeZone): LocalDate = |
| 37 | + now().toLocalDateTime(timeZone).date |
| 38 | + |
| 39 | +/** |
| 40 | + * Returns a [TimeSource] that uses this [Clock] to mark a time instant and to find the amount of time elapsed since that mark. |
| 41 | + */ |
| 42 | +@ExperimentalTime |
| 43 | +public fun Clock.asTimeSource(): TimeSource = object : TimeSource { |
| 44 | + override fun markNow(): TimeMark = InstantTimeMark(now(), this@asTimeSource) |
| 45 | +} |
| 46 | + |
| 47 | +@ExperimentalTime |
| 48 | +private class InstantTimeMark(private val instant: Instant, private val clock: Clock) : TimeMark { |
| 49 | + override fun elapsedNow(): Duration = clock.now() - instant |
| 50 | + |
| 51 | + override fun plus(duration: Duration): TimeMark = InstantTimeMark(instant + duration, clock) |
| 52 | + |
| 53 | + override fun minus(duration: Duration): TimeMark = InstantTimeMark(instant - duration, clock) |
| 54 | +} |
| 55 | + |
| 56 | +@Deprecated("Use Clock.todayIn instead", ReplaceWith("this.todayIn(timeZone)"), DeprecationLevel.WARNING) |
| 57 | +public fun Clock.todayAt(timeZone: TimeZone): LocalDate = todayIn(timeZone) |
0 commit comments