parse

expect fun parse(input: CharSequence, format: DateTimeFormat<LocalDateTime> = getIsoDateTimeFormat()): LocalDateTime(source)

A shortcut for calling DateTimeFormat.parse.

Parses a string that represents a datetime value including date and time components but without any time zone component and returns the parsed LocalDateTime value.

If format is not specified, Formats.ISO is used. 2023-01-02T23:40:57.120 is an example of a string in this format.

See Formats and Format for predefined and custom formats.

Throws

if the text cannot be parsed or the boundaries of LocalDateTime are exceeded.

Samples

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

fun main() { 
   //sampleStart 
   // Parsing LocalDateTime values using predefined and custom formats
check(LocalDateTime.parse("2024-02-15T08:30:15.123456789") ==
    LocalDate(2024, 2, 15).atTime(8, 30, 15, 123_456_789))
check(LocalDateTime.parse("2024-02-15T08:30") ==
    LocalDate(2024, 2, 15).atTime(8, 30))
val customFormat = LocalDateTime.Format {
    date(LocalDate.Formats.ISO)
    char(' ')
    hour(); char(':'); minute(); char(':'); second()
    char(','); secondFraction(fixedLength = 3)
}
check(LocalDateTime.parse("2024-02-15 08:30:15,123", customFormat) ==
    LocalDate(2024, 2, 15).atTime(8, 30, 15, 123_000_000)) 
   //sampleEnd
}