Skip to content

Instantly share code, notes, and snippets.

@Daemon-Devarshi
Created October 22, 2020 14:45
Show Gist options
  • Save Daemon-Devarshi/077698a2dc9b63f9b8322460973a59ba to your computer and use it in GitHub Desktop.
Save Daemon-Devarshi/077698a2dc9b63f9b8322460973a59ba to your computer and use it in GitHub Desktop.
Property wrappers to serialise date
extension Date {
static let decodeFormats: [String] = ["yyyy-MM-dd'T'HH:mm:ss.SSSZ"]
func encodedDateString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter.string(from: self)
}
}
extension String {
func decodedDate() -> Date? {
let formatter = DateFormatter()
var value: Date?
Date.decodeFormats.forEach {
formatter.dateFormat = $0
if let date = formatter.date(from: self) {
value = date
return
}
}
return value
}
}
@propertyWrapper
public struct OptionalCodableDate: Codable {
public var wrappedValue: Date?
public init(wrappedValue: Date?) {
self.wrappedValue = wrappedValue
}
public init(from decoder: Decoder) throws {
// String to date
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
if let value = dateString.decodedDate() {
wrappedValue = value
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateString)")
}
}
public func encode(to encoder: Encoder) throws {
guard let wrappedValue = wrappedValue else {
return
}
// Date to string
var container = encoder.singleValueContainer()
try container.encode(wrappedValue.encodedDateString())
}
}
@propertyWrapper
public struct CodableDate: Codable {
public var wrappedValue: Date
public init(wrappedValue: Date) {
self.wrappedValue = wrappedValue
}
public init(from decoder: Decoder) throws {
// String to date
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
if let value = dateString.decodedDate() {
wrappedValue = value
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateString)")
}
}
public func encode(to encoder: Encoder) throws {
// Date to string
var container = encoder.singleValueContainer()
try container.encode(wrappedValue.encodedDateString())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment