Library contents

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

  1. Start with 90 seconds
  2. Do this Express in minutes and seconds
  3. Result 1 minute, 30 seconds
Sixty seconds make one full minute and thirty seconds remain.

Syntax

Kotlin 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.

From the programval elapsed = 125.seconds
First output line2 min 5 s
Lesson.kt
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)
}
Output
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

Advertisements

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.

Given3750 ms → whole seconds
Worked result3

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.

Given820 ms → whole seconds
Worked result0