Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting kotlin time Duration

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?

like image 327
user2424380 Avatar asked Aug 02 '26 11:08

user2424380


2 Answers

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
}
like image 112
EunhaEonnie Avatar answered Aug 07 '26 00:08

EunhaEonnie


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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!