format

Uses this format to format an unstructured DateTimeComponents.

block is called on an initially-empty DateTimeComponents before formatting.

Example:

// Mon, 16 Mar 2020 23:59:59 +0300
DateTimeComponents.Formats.RFC_1123.format {
setDateTime(LocalDateTime(2020, 3, 16, 23, 59, 59, 999_999_999))
setOffset(UtcOffset(hours = 3))
}

Throws

if some values needed for the format are not present or can not be formatted: for example, trying to format DateTimeFormatBuilder.WithDate.monthName using a DateTimeComponents.monthNumber value of 20.

Samples

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

fun main() { 
   //sampleStart 
   // Formatting partial, complex, or broken data
// DateTimeComponents can be used to format 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(); char(':'); offsetSecondsOfMinute()
}
val formattedCompoundData = compoundFormat.format {
    setDate(LocalDate(2023, 1, 2))
    setTime(LocalTime(3, 46, 58, 531_000_000))
    setOffset(UtcOffset(3, 30))
}
check(formattedCompoundData == "2023-01-02 03:46:58.531 +03:30:00")
// It can also be used to format partial data that is missing some components
val partialFormat = DateTimeComponents.Format {
    year(); char('-'); monthNumber()
}
val formattedPartialData = partialFormat.format {
    year = 2023
    month = Month.JANUARY
}
check(formattedPartialData == "2023-01") 
   //sampleEnd
}