Time Formatting Parsing in Swift

Swift supports time formatting and parsing via pattern-based layouts.

import Foundation

func main() {
    let p = { (items: Any...) in
        items.forEach { print($0) }
    }

    // Here's a basic example of formatting a time
    // according to ISO8601, which is similar to RFC3339.
    let t = Date()
    p(ISO8601DateFormatter().string(from: t))

    // Time parsing uses a DateFormatter for custom formats.
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    if let t1 = dateFormatter.date(from: "2012-11-01T22:08:41+00:00") {
        p(t1)
    }

    // Format and parse use example-based layouts. Usually
    // you'll use a constant from DateFormatter.Style for these layouts, but
    // you can also supply custom layouts. Layouts must use the
    // date format patterns as specified in Unicode Technical Standard #35.
    
    let customFormatter = DateFormatter()
    customFormatter.dateFormat = "h:mma"
    p(customFormatter.string(from: t))
    
    customFormatter.dateFormat = "E MMM d HH:mm:ss yyyy"
    p(customFormatter.string(from: t))
    
    customFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
    p(customFormatter.string(from: t))
    
    customFormatter.dateFormat = "h mm a"
    if let t2 = customFormatter.date(from: "8 41 PM") {
        p(t2)
    }

    // For purely numeric representations you can also
    // use standard string formatting with the extracted
    // components of the time value.
    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: t)
    print(String(format: "%04d-%02d-%02dT%02d:%02d:%02d-00:00",
                 components.year!, components.month!, components.day!,
                 components.hour!, components.minute!, components.second!))

    // DateFormatter will return nil on malformed input.
    customFormatter.dateFormat = "E MMM d HH:mm:ss yyyy"
    if let _ = customFormatter.date(from: "8:41PM") {
        p("Parsed successfully")
    } else {
        p("Failed to parse")
    }
}

main()

This Swift code demonstrates time formatting and parsing, which is conceptually similar to the Go example, but uses Swift’s Foundation framework and its Date, DateFormatter, and ISO8601DateFormatter types.

Key differences and notes:

  1. Swift uses DateFormatter for most custom date formatting and parsing tasks.
  2. The ISO8601DateFormatter is used for ISO8601/RFC3339-like formatting.
  3. Swift’s date format strings follow the Unicode Technical Standard #35, which is different from Go’s layout strings.
  4. Error handling in Swift for date parsing typically involves optional binding or force unwrapping, as DateFormatter.date(from:) returns an optional Date?.
  5. Swift doesn’t have a direct equivalent to Go’s time.Parse() function. Instead, you configure a DateFormatter and use its date(from:) method.
  6. The Calendar type is used to extract individual components from a Date.

When running this code, you’ll see output similar to the Go example, with formatted dates and times according to various patterns.