Time Formatting Parsing in Kotlin

import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

fun main() {
    // Here's a basic example of formatting a time
    // according to ISO_DATE_TIME, which is similar to RFC3339
    val now = ZonedDateTime.now()
    println(now.format(DateTimeFormatter.ISO_DATE_TIME))

    // Time parsing uses the same formatter as formatting
    val t1 = ZonedDateTime.parse("2012-11-01T22:08:41+00:00", DateTimeFormatter.ISO_DATE_TIME)
    println(t1)

    // Custom formatting patterns can be defined using DateTimeFormatter
    println(now.format(DateTimeFormatter.ofPattern("h:mma")))
    println(now.format(DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy")))
    println(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSVV")))

    // Parsing with custom patterns
    val form = DateTimeFormatter.ofPattern("h mm a")
    val t2 = LocalDateTime.parse("8 41 PM", form)
    println(t2)

    // For purely numeric representations you can also
    // use string formatting with the extracted components of the time value
    println("%d-%02d-%02dT%02d:%02d:%02d-00:00".format(
        now.year, now.monthValue, now.dayOfMonth,
        now.hour, now.minute, now.second
    ))

    // Parsing will throw an exception on malformed input
    try {
        val ansic = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy")
        LocalDateTime.parse("8:41PM", ansic)
    } catch (e: Exception) {
        println("Error parsing time: ${e.message}")
    }
}

This Kotlin code demonstrates time formatting and parsing using the java.time package, which is the modern way to handle dates and times in Kotlin (and Java).

Here are some key points about the translation:

  1. Kotlin uses ZonedDateTime and LocalDateTime classes instead of a single time type.

  2. The DateTimeFormatter class is used for both formatting and parsing.

  3. Kotlin doesn’t have predefined constants for time formats like RFC3339, so we use ISO_DATE_TIME which is similar.

  4. Custom format patterns in Kotlin use similar syntax to Go, but are defined using DateTimeFormatter.ofPattern().

  5. Error handling in Kotlin typically uses exceptions, so we use a try-catch block to demonstrate error handling in time parsing.

  6. Kotlin’s string formatting uses a syntax similar to printf, with %d for integers and %02d for zero-padded integers.

When you run this program, it will output various formatted dates and times, parsed times, and an error message for the malformed input, similar to the original Go program.

Remember that the exact output will depend on the current time when you run the program.