Blog Infos

Kotlin 1.9.0 relased on August 23, 2023.
In addition to the new features, experimental features from earlier versions are now stable.
In today’s article, we will explore the stable Time API
Duration is stable since version 1.6.0
Major functions/interfaces/classes
- markNow()— Marks a point in time on the given time source.
val valueTimeMark1 = TimeSource.Monotonic.markNow()
- measureTime()— It
returnsthe duration of the elapsed time interval afterexecutingthe given function block. - measureTimedValue() — It returns the duration as well as the result of the function execution
- TimeSource — It’s an
interfacewhichprovidesthe followingmethods
markNow(), measureTime(), measureTimedValue()
- TimeMark — It’s an
interfacewhichprovidesthe followingmethods - hasNotPassedNow()— Returns
true, If the given time mark has not passed yet. - hasPassedNow() — Returns
trueif the time mark has passed based on the time source from which it was taken.
Sample code
By default measureTime() as well as measureTimedValue() both use a Monotonictime source.
If you want to override this behavior you can by implementing AbstractLongTimeSource .
Please check this example to see how we can use SystemClock.elapsedRealtimeNanos() in the case of Android
measureTime()
fun calculateProcessingTime() {
val duration = measureTime {
for (i in 0..<100) {
println(i)
}
}
println(duration)
}
measureTimedValue()
- Learn more about destructuring declarations here
val sumOfTwoNums = { num1: Int, num2: Int ->
num1 + num2
}
fun getResultAndTime() {
// destructuring
val (value, duration1) = TimeSource.Monotonic.measureTimedValue {
sumOfTwoNums(5, 7)
}
println("Result value: $value")
println("Time took: $duration1")
}
Mark and measure differences in time
Mark a specific moment
- You can read more about Monotonic time here
val timeSource = TimeSource.Monotonic val mark1 = TimeSource.Monotonic.markNow()
Measure differences in time ⏰
val timeSource = TimeSource.Monotonic
val valueTimeMark1 = TimeSource.Monotonic.markNow()
Thread.sleep(5000) // 5 seconds
val valueTimeMarkAfter5Seconds = timeSource.markNow()
println(valueTimeMarkAfter5Seconds > valueTimeMark1) // true
Job Offers
Getting duration components
48.days.toComponents { days, hours, minutes, seconds, nanoseconds ->
// process each unit here as per your requirements
}
Checking if the time mark has passed or not
hasPassedNow()
val valueTimeMark1 = TimeSource.Monotonic.markNow() val valueTimeMark2 = valueTimeMark1 + 2.seconds println(alueTimeMark2.hasPassedNow()) // true || false
hasNotPassedNow()
val valueTimeMark1 = TimeSource.Monotonic.markNow() val valueTimeMark2 = valueTimeMark1 + 2.seconds println(valueTimeMark2.hasNotPassedNow()) // true || false
References
Kotlin 1.9.0 relased on August 23, 2023. In addition to the new features, experimental features from earlier versions are now stable.



