toString

open override fun toString(): String(source)

Returns a string representation of this duration value expressed as a combination of numeric components, each in its own unit.

Each component is a number followed by the unit abbreviated name: d, h, m, s: 5h, 1d 12h, 1h 0m 30.340s. The last component, usually seconds, can be a number with a fractional part.

If the duration is less than a second, it is represented as a single number with one of sub-second units: ms (milliseconds), us (microseconds), or ns (nanoseconds): 140.884ms, 500us, 24ns.

A negative duration is prefixed with - sign and, if it consists of multiple components, surrounded with parentheses: -12m and -(1h 30m).

Special cases:

  • an infinite duration is formatted as "Infinity" or "-Infinity" without a unit.

It's recommended to use toIsoString that uses more strict ISO-8601 format instead of this toString when you want to convert a duration to a string in cases of serialization, interchange, etc.

Since Kotlin

1.6

Samples

import kotlin.test.*
import kotlin.time.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.Duration.Companion.seconds

fun main() { 
   //sampleStart 
   println(45.days) // 45d
println(1.5.days) // 1d 12h
println(1230.minutes) // 20h 30m
println(920.minutes) // 15h 20m
println(1.546.seconds) // 1.546s
println(25.12.milliseconds) // 25.12ms 
   //sampleEnd
}

fun toString(unit: DurationUnit, decimals: Int = 0): String(source)

Returns a string representation of this duration value expressed in the given unit and formatted with the specified decimals number of digits after decimal point.

Special cases:

  • an infinite duration is formatted as "Infinity" or "-Infinity" without a unit.

Since Kotlin

1.6

Return

the value of duration in the specified unit followed by that unit abbreviated name: d, h, m, s, ms, us, or ns.

Parameters

decimals

the number of digits after decimal point to show. The value must be non-negative. No more than 12 decimals will be shown, even if a larger number is requested.

Throws

if decimals is less than zero.

Samples

import kotlin.test.*
import kotlin.time.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.Duration.Companion.seconds

fun main() { 
   //sampleStart 
   println(1230.minutes.toString(DurationUnit.DAYS, 2)) // 0.85d
println(1230.minutes.toString(DurationUnit.HOURS, 2)) // 20.50h
println(1230.minutes.toString(DurationUnit.MINUTES)) // 1230m
println(1230.minutes.toString(DurationUnit.SECONDS)) // 73800s 
   //sampleEnd
}