Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I truncate a Kotlin Duration?

Tags:

kotlin

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 MINUTES unit 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
}
like image 615
aSemy Avatar asked Oct 29 '25 01:10

aSemy


1 Answers

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)
like image 175
Sam Avatar answered Oct 30 '25 23:10

Sam