Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Last active September 22, 2017 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimpiax/3b6317cc86dbee05abd6563de2a2a581 to your computer and use it in GitHub Desktop.
Save dimpiax/3b6317cc86dbee05abd6563de2a2a581 to your computer and use it in GitHub Desktop.
Swift custom date decoder. ISO8601 without milliseconds
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom { decoder -> Date in
let valueContainer = try decoder.singleValueContainer()
let value = try valueContainer.decode(String.self)
if let regex = try? NSRegularExpression(pattern: "\\.\\d+", options: []) {
let result = regex.stringByReplacingMatches(in: value, options: [], range: NSRange(location: 0, length: value.count), withTemplate: "")
if let date = ISO8601DateFormatter().date(from: result) {
return date
}
}
let context = DecodingError.Context(codingPath: valueContainer.codingPath, debugDescription: "Invalid date")
throw DecodingError.dataCorrupted(context)
}
// decodes 1970-01-01T00:00:00.111Z as 1970-01-01T00:00:00Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment