Skip to content

Instantly share code, notes, and snippets.

@Ravi61
Created July 13, 2017 15:16
Show Gist options
  • Save Ravi61/5d60d7fd6eac689cea81aeda4f318614 to your computer and use it in GitHub Desktop.
Save Ravi61/5d60d7fd6eac689cea81aeda4f318614 to your computer and use it in GitHub Desktop.
Custom Date Encoding/Decoding
// 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