Java's Duration has a truncate function.
Duration d = myDuration.truncatedTo(ChronoUnit.SECONDS);
public Duration truncatedTo(TemporalUnit unit)Returns a copy of this Duration truncated to the specified unit.
Truncating the duration returns a copy of the original with conceptual fields smaller than the specified unit set to zero. For example, truncating with the
MINUTESunit will round down to the nearest minute, setting the seconds and nanoseconds to zero.
However Kotlin has a different implementation for Duration, and this does not have an analogous truncation method.
I want to be able to divide or multiply a Duration by some number, and then (with an extension function) remove any time unit smaller than the one I supply.
import kotlin.time.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
fun main() {
   val duration = 10.days + 5.hours + 33.minutes
   println(duration)
   val divided = duration / 100.001
   println(divided)
   val truncatedToSeconds = divided.truncate(DurationUnit.SECONDS)
   println(truncatedToSeconds) // expect: 2h 27m 19s
   
   val truncatedToMinutes = divided.truncate(DurationUnit.MINUTES)
   println(truncatedToMinutes) // expect: 2h 27m
   val truncatedToHours = divided.truncate(DurationUnit.HOURS)
   println(truncatedToHours) // expect: 2h
}
fun Duration.truncate(unit: DurationUnit): Duration {
   /// ...
   return this
}
One option is to convert it to a Long and back again, using your desired unit:
fun Duration.truncate(unit: DurationUnit): Duration =
    toLong(unit).toDuration(unit)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With