parseOrNull

Parses a string that represents a duration and returns the parsed Duration value, or null if the string doesn't represent a duration in any of the supported formats.

The following formats are accepted:

  • Restricted ISO-8601 duration composite representation, e.g. P1DT2H3M4.058S, see toIsoString and parseIsoString.

  • The format of string returned by the default Duration.toString and toString in a specific unit, e.g. 10s, 1h 30m or -(1h 30m).

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 
   val isoFormatString = "PT1H30M"
val defaultFormatString = "1h 30m"
val singleUnitFormatString = "1.5h"
val invalidFormatString = "1 hour 30 minutes"

println(Duration.parse(isoFormatString)) // 1h 30m
println(Duration.parse(defaultFormatString)) // 1h 30m
println(Duration.parse(singleUnitFormatString)) // 1h 30m
// Duration.parse(invalidFormatString) // will fail
println(Duration.parseOrNull(invalidFormatString)) // null 
   //sampleEnd
}