Format
fun Format(block: DateTimeFormatBuilder.WithDateTimeComponents.() -> Unit): DateTimeFormat<DateTimeComponents>(source)
Creates a DateTimeFormat for DateTimeComponents values using DateTimeFormatBuilder.WithDateTimeComponents.
There is a collection of predefined formats in DateTimeComponents.Formats.
Throws
if parsing using this format is ambiguous.
Samples
import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.test.*
fun main() {
//sampleStart
// Formatting and parsing a complex entity with a custom format
val customFormat = DateTimeComponents.Format {
date(LocalDate.Formats.ISO)
char(' ')
hour(); char(':'); minute(); char(':'); second(); char('.'); secondFraction(3)
char(' ')
offset(UtcOffset.Formats.FOUR_DIGITS)
}
val formatted = customFormat.format {
setDate(LocalDate(2023, 1, 2))
setTime(LocalTime(3, 46, 58, 530_000_000))
setOffset(UtcOffset(3, 30))
}
check(formatted == "2023-01-02 03:46:58.530 +0330")
val parsed = customFormat.parse("2023-01-31 24:00:00.530 +0330").apply {
// components can be out of bounds
if (hour == 24 && minute == 0 && second == 0) {
setTime(LocalTime(0, 0))
setDate(toLocalDate().plus(1, DateTimeUnit.DAY))
}
}
check(parsed.toLocalDate() == LocalDate(2023, 2, 1))
check(parsed.toLocalTime() == LocalTime(0, 0))
check(parsed.toUtcOffset() == UtcOffset(3, 30))
//sampleEnd
}