parse

Parses a DateTimeComponents from input using the given format. Equivalent to calling DateTimeFormat.parse on format with input.

DateTimeComponents does not perform any validation, so even invalid values may be parsed successfully if the string pattern matches.

Throws

if the text does not match the format.

Samples

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

fun main() { 
   //sampleStart 
   // Parsing partial, complex, or broken data
// DateTimeComponents can be used to parse complex data that consists of multiple components
val compoundFormat = DateTimeComponents.Format {
    date(LocalDate.Formats.ISO)
    char(' ')
    hour(); char(':'); minute(); char(':'); second(); char('.'); secondFraction(3)
    char(' ')
    offsetHours(); char(':'); offsetMinutesOfHour(); optional { char(':'); offsetSecondsOfMinute() }
}
val parsedCompoundData = DateTimeComponents.parse("2023-01-02 03:46:58.531 +03:30", compoundFormat)
check(parsedCompoundData.toLocalTime() == LocalTime(3, 46, 58, 531_000_000))
check(parsedCompoundData.toLocalDate() == LocalDate(2023, 1, 2))
check(parsedCompoundData.toUtcOffset() == UtcOffset(3, 30))
check(parsedCompoundData.toInstantUsingOffset() == Instant.parse("2023-01-02T03:46:58.531+03:30"))
// It can also be used to parse partial data that is missing some components
val partialFormat = DateTimeComponents.Format {
    year(); char('-'); monthNumber()
}
val parsedPartialData = DateTimeComponents.parse("2023-01", partialFormat)
check(parsedPartialData.year == 2023)
check(parsedPartialData.month == Month.JANUARY)
try {
    parsedPartialData.toLocalDate()
    fail("Expected an exception")
} catch (e: IllegalArgumentException) {
    // expected: the day is missing, so LocalDate cannot be constructed
} 
   //sampleEnd
}