Skip to content

Instantly share code, notes, and snippets.

@vani2
Last active March 3, 2021 08:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vani2/5fe916b45afcaba7c8c2143ac056adea to your computer and use it in GitHub Desktop.
Save vani2/5fe916b45afcaba7c8c2143ac056adea to your computer and use it in GitHub Desktop.
Date Decoding Strategy
import Foundation
struct ISODateModel: Codable {
let date: Date
}
var json = """
{
"date": "2018-04-20T14:20:00-0700"
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let isoModel = try decoder.decode(ISODateModel.self, from: json)
print(isoModel.date) //2018-04-20 21:20:00 +0000
struct UnixDateModel: Codable {
let date: Date
}
json = """
{
"date": 1213213123
}
""".data(using: .utf8)!
decoder.dateDecodingStrategy = .secondsSince1970
let unixModel = try decoder.decode(UnixDateModel.self, from: json)
print(unixModel.date) //2008-06-11 19:38:43 +0000
decoder.dateDecodingStrategy = .custom { decoder -> Date in
let container = try decoder.singleValueContainer()
let unixTime = try container.decode(Double.self)
let date = Date(timeIntervalSince1970: unixTime)
return date.addingTimeInterval(120)
}
let customUnixModel = try decoder.decode(UnixDateModel.self, from: json)
print(customUnixModel.date) //2008-06-11 19:38:43 +0000
struct FormattedDateModel: Codable {
let date: Date
}
json = """
{
"date": "08-31-2018 18:49"
}
""".data(using: .utf8)!
let dateFormatted = DateFormatter()
dateFormatted.dateFormat = "MM-dd-yyyy HH:mm"
decoder.dateDecodingStrategy = .formatted(dateFormatted)
let formattedModel = try decoder.decode(FormattedDateModel.self, from: json)
print(formattedModel.date) //2018-08-31 15:49:00 +0000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment