Last active
February 12, 2021 09:41
-
-
Save shaps80/865a0a58eb66bc991881dd9833046df0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}() | |
} |
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
better: ISO8601DateFormatter
Yes, this is an old GIST :)
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
better: ISO8601DateFormatter