Is there any convenient way to format kotlin.time.Duration to string as I can do with LocalDateTime and DateTimeFormatter?
For example:
val time = LocalDateTime.now()
d.format(DateTimeFormatter.ofPattern("mm:ss")
I know about Duration's absoluteValue, but it doesn't round values, i.e. I got durations like
3m 19.1666666666s
Thank you in advance!
Edit: What I have tried:
val x = 333.333333333333.toDuration(DurationUnit.SECONDS)
println(z.absoluteValue) //55m 33.33333333s
println(z.inWholeSeconds) //3333
println(z.inWholeMinutes) //55
println(z.toString(DurationUnit.MINUTES, 2) // 55,56m
What I've found and closest to what I need: How can I truncate a Kotlin Duration?
You can use toComponents function the toComponents function will splits the duration into hours, minutes, seconds, and nanoseconds and executes the given action.
fun main() {
val time = 3329.seconds
println(
time.toComponents { hours, minutes, seconds, nanoseconds ->
"$hours:$minutes:$seconds"
}
) // 0:55:29
}
You can use the inWhole* properties of the Duration class. So in your example, a duration of 3m19.1666s would be duration.inWholeSeconds -> 3m19s or duration.inWholeMinutes -> 3m.
If you want to make use of Duration's toString, simply convert back to a Duration: duration.inWholeSeconds.seconds.toString() -> prints 3m19s
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