Last active
September 22, 2017 12:47
-
-
Save dimpiax/3b6317cc86dbee05abd6563de2a2a581 to your computer and use it in GitHub Desktop.
Swift custom date decoder. ISO8601 without milliseconds
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
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