Created
July 13, 2017 15:16
-
-
Save Ravi61/5d60d7fd6eac689cea81aeda4f318614 to your computer and use it in GitHub Desktop.
Custom Date Encoding/Decoding
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
// Custom Date Decoding | |
jsonDecoder.dateDecodingStrategy = .custom({ (decoder) -> Date in | |
let data = try decoder.singleValueContainer().decode(String.self) | |
//perform your operation on obtained string | |
let disturbance = "01-07-1977" | |
let formatter = DateFormatter() | |
formatter.dateFormat = "dd-MM-yyyy" | |
if data == "First disturbance in force" { | |
return formatter.date(from: disturbance) ?? Date() | |
} else { | |
return Date() | |
} | |
}) | |
// Custom Date Encoding | |
jsonEncoder.dateEncodingStrategy = .custom({ (date, encoder) in | |
let formatter = DateFormatter() | |
formatter.dateFormat = "dd-MM-yyyy" | |
let stringData = formatter.string(from: date) | |
var container = encoder.singleValueContainer() | |
try container.encode(stringData) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment