toString

Common
JVM
JS
Native
1.0
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.3340s. 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.

import kotlin.time.*

fun main(args: Array<String>) {
//sampleStart
println(Duration.days(45)) // 45d
println(Duration.days(1.5)) // 1d 12h
println(Duration.minutes(1230)) // 20h 30m
println(Duration.minutes(920)) // 15h 20m
println(Duration.seconds(1.546)) // 1.546s
println(Duration.milliseconds(25.12)) // 25.12ms
//sampleEnd
}
Common
JVM
JS
Native
1.0
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.
import kotlin.time.*

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

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.

Exceptions

IllegalArgumentException - if decimals is less than zero.

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