alternative Parsing
fun <T : DateTimeFormatBuilder> T.alternativeParsing(vararg alternativeFormats: T.() -> Unit, primaryFormat: T.() -> Unit)(source)
A format along with other ways to parse the same portion of the value.
When parsing, first, primaryFormat is used; if parsing the whole string fails using that, the formats from alternativeFormats are tried in order.
When formatting, the primaryFormat is used to format the value, and alternativeFormats are ignored.
Example:
alternativeParsing(
{ dayOfMonth(); char('-'); monthNumber() },
{ monthNumber(); char(' '); dayOfMonth() },
) { monthNumber(); char('/'); dayOfMonth() }
Content copied to clipboard
This will always format a date as MM/DD
, but will also accept DD-MM
and MM DD
.
Samples
import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.test.*
fun main() {
//sampleStart
// Defining a custom format that allows parsing one of several alternatives
val format = DateTimeComponents.Format {
// optionally, date:
alternativeParsing({
}) {
date(LocalDate.Formats.ISO)
}
// optionally, time:
alternativeParsing({
}) {
// either the `T` or the `t` character:
alternativeParsing({ char('t') }) { char('T') }
time(LocalTime.Formats.ISO)
}
}
val date = LocalDate(2020, 1, 13)
val time = LocalTime(12, 30, 16)
check(format.parse("2020-01-13t12:30:16").toLocalDateTime() == date.atTime(time))
check(format.parse("2020-01-13").toLocalDate() == date)
check(format.parse("T12:30:16").toLocalTime() == time)
check(format.format { setDate(date); setTime(time) } == "2020-01-13T12:30:16")
//sampleEnd
}