toString
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.
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(args: Array<String>) {
//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
}
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.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(args: Array<String>) {
//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
}
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
.