parseOrNull

abstract fun parseOrNull(input: CharSequence): T?(source)

Parses the given input string as T using this format.

Return

the parsed value, or null if the input string is not in the expected format or the value is invalid.

Samples

import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   // Attempting to parse a string that may not be in the expected format
check(LocalDate.Formats.ISO.parseOrNull("2021-02-07") == LocalDate(2021, 2, 7))
check(LocalDate.Formats.ISO.parseOrNull("2021-02-07T") == null)
check(LocalDate.Formats.ISO.parseOrNull("2021-02-40") == null)
check(LocalDate.Formats.ISO.parseOrNull("2021-02-40") == null)
// to parse strings that have valid formats but invalid values, use `DateTimeComponents`:
val dateTimeComponentsFormat = DateTimeComponents.Format { date(LocalDate.Formats.ISO) }
check(dateTimeComponentsFormat.parseOrNull("2021-02-40")?.dayOfMonth == 40) 
   //sampleEnd
}