kotlin's `Duration` has no `.between()` to get a d...
# announcements
t
kotlin's
Duration
has no
.between()
to get a duration between instances. which is fine... but once I include the
java.time.Duration
all the nice kotlin extension functions like
Int.inSeconds
can't be found. Am I just stuck w/ the java ones if I need
between()
?
t
that's for another duration. not getting a duration between two `instant`s
unless instant extend duration?
h
create a range and use the in operator
t
I'm not aware of a time-range. Is that maybe a JS thing? I'm targeting JVM.
h
Copy code
val upper = 5.seconds
val lower = 2.seconds
if (3.seconds in lower..upper) {
    println("true 3")
}
if (1.seconds !in lower..upper) {
    println("true 1")
}
r
I had this issue too, and I need an actual Duration not a range. My solution was to alias import e.g.
import java.time.Duration as JavaTimeDuration
.
You can combine that import with an extension function on kotlin's Duration, so that you only need it one place.
t
@rocketraman thanks!
@hfhbd There is no use of an instant in your example. I'm trying to do this :
val start = Instant.now()
[... do something, time passes ... ]
val end = Instant.now()
val delta = Duration.between(start,end)
The kotlin duration doesn't have
between()
r
@TwoClocks I do it like this:
Copy code
fun ClosedRange<Instant>.duration(): Duration =
  JavaTimeDuration.between(start, endInclusive).toKotlinDuration()
which you can then use like this:
Copy code
(start..end).duration()
As you've noted the Kotlin API so far has no way to subtract or add two `Instant`'s to get a Kotlin
Duration
, so I believe that is the best approach.
BTW, if all you're trying to do is measure how long that "do something" code takes, you could do instead:
Copy code
val duration = measureTime { ... do something ... }
Or if that block returns a value
measureTimedValue
like this:
Copy code
val (result, duration) = measureTimedValue { ... do something ... }