Skip to content

Instantly share code, notes, and snippets.

@shaps80
Last active February 12, 2021 09:41
Show Gist options
  • Save shaps80/865a0a58eb66bc991881dd9833046df0 to your computer and use it in GitHub Desktop.
Save shaps80/865a0a58eb66bc991881dd9833046df0 to your computer and use it in GitHub Desktop.
// Swift 3
extension DateFormatter {
public static var iso8601: DateFormatter {
return DateFormatter.iso8601DateFormatter
}
private static let iso8601DateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()
}
// Swift 2.2
extension NSDateFormatter {
public static var iso8601: NSDateFormatter {
return NSDateFormatter.iso8601DateFormatter
}
private static let iso8601DateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()
}
@SeRG1k17
Copy link

better: ISO8601DateFormatter

@muellerando
Copy link

better: ISO8601DateFormatter

Do you know how to convert an ISO8601DateFormatter into DateFormatter?
ISO8601DateFormatter inherits from Formatter wich is not compliant to DateFormatter, so I cannot set the ISO Formatter into
encoder.dateEncodingStrategy for Decoding & Encoding JSONs

@shaps80
Copy link
Author

shaps80 commented Feb 12, 2021

better: ISO8601DateFormatter

Yes, this is an old GIST :)

@shaps80
Copy link
Author

shaps80 commented Feb 12, 2021

better: ISO8601DateFormatter

Do you know how to convert an ISO8601DateFormatter into DateFormatter?
ISO8601DateFormatter inherits from Formatter wich is not compliant to DateFormatter, so I cannot set the ISO Formatter into
encoder.dateEncodingStrategy for Decoding & Encoding JSONs

Actually this is already built in:

decoder.dateEncodingStrategy = .iso8601

Also if you need to customise the formatter you can do it via .custom

encoder.dateEncodingStrategy = .custom { date, encoder in
    var container = encoder.singleValueContainer()
    let formatter = ISO8601DateFormatter()
    formatter.formatOptions = .withColonSeparatorInTime
    try container.encode(formatter.string(from: date))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment