Kotlin Duration and inWholeMinutes
Kotlin Duration represents an elapsed interval. inWholeMinutes returns complete minutes and duration arithmetic can recover the remainder.
A simple example
Duration and inWholeMinutes
- Start with 90 seconds
- Do this Express in minutes and seconds
- Result 1 minute, 30 seconds
Syntax
val remaining = elapsed - elapsed.inWholeMinutes.minutes
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Split elapsed time into whole minutes and seconds
A scheduler receives durations in one unit but reports or retries in another. Track the whole units and any fractional part before turning the original delay into a displayed time or retry budget.
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Duration.Companion.minutes
fun main() {
val elapsed = 125.seconds
val whole = elapsed.inWholeMinutes
val rest = elapsed - whole.minutes
println("$whole min " + rest.inWholeSeconds + " s")
println((-30).seconds.inWholeMinutes)
}
2 min 5 s 0
Whole-unit conversions truncate toward zero. This example uses a nonnegative elapsed time, so the remaining seconds fall between zero and 59.
Kotlin documentation for Duration and inWholeMinutes
Time a school animation
A student’s animation runs for 3750 milliseconds. Convert the elapsed milliseconds to complete seconds. Leave the fractional second out of the display.
Time a ticket scan
A fast ticket scan takes 820 milliseconds. Convert the elapsed milliseconds to complete seconds. Leave the fractional second out of the display.