to String
Converts this period to the ISO 8601 string representation for durations, for example, P2M1DT3H
.
Note that the ISO 8601 duration is not the same as Duration, but instead includes the date components, like DateTimePeriod does.
Examples of the output:
P2Y4M-1D
: two years, four months, minus one day;-P2Y4M1D
: minus two years, minus four months, minus one day;P1DT3H2M4.123456789S
: one day, three hours, two minutes, four seconds, 123456789 nanoseconds;P1DT-3H-2M-4.123456789S
: one day, minus three hours, minus two minutes, minus four seconds, minus 123456789 nanoseconds;
See ISO-8601-1:2019, 5.5.2.2a)
See also
for the detailed description of the format.
Samples
import kotlinx.datetime.*
import kotlin.test.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
fun main() {
//sampleStart
// Formatting a DateTimePeriod to a string
check(DateTimePeriod(years = 1, months = 2, days = 3, hours = 4, minutes = 5, seconds = 6, nanoseconds = 7).toString() == "P1Y2M3DT4H5M6.000000007S")
check(DateTimePeriod(months = 14, days = -16, hours = 5).toString() == "P1Y2M-16DT5H")
check(DateTimePeriod(months = -2, days = -16, hours = -5).toString() == "-P2M16DT5H")
//sampleEnd
}