Home > Blockchain >  swift Encodable override encode with 2 different dateformats
swift Encodable override encode with 2 different dateformats

Time:10-25

I have class conforming to Encodable which contains 2 date properties. When I'm encoding it to string I'd like these 2 dates to use different date formatting - for example

Optional("{\n "date1" : "2022-10-24T22:03:43Z",\n "date2" : 688342014.16646099\n}")

but I cant figure out how to do it, heres example code

  func getString() -> String? {
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    encoder.dateEncodingStrategy = .iso8601
    
    guard let data = try? encoder.encode(TwoDates()) else { return nil }
    guard let dataString = String(data: data, encoding: .utf8) else { return nil }
    return dataString
  }
class TwoDates: Encodable {
  public var date1 = Date()
  public var date2 = Date()
  
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try? container.encode(date1, forKey: .date1)
    try? container.encode(date1, forKey: .date2)
  }
  
  enum CodingKeys: String, CodingKey {
    case date1 = "date1"
    case date2 = "date2"
  }
}

So, how to use different date formatters for 2 different properties? Should I somehow override JSONEncoder.encode()?

CodePudding user response:

You're already encoding a date object; sounds like what you want is to decode into separate formats. For that just override your decode and use DateFormatter() objects. You can find docs and examples here https://developer.apple.com/documentation/foundation/dateformatter If you want to archive as another object you could use the formatter in encode override. Keep in mind the payload will be larger that way though.

CodePudding user response:

Its actually so simple I cant believe it, just need to provide dateformat on encoding, i.e

    try? container.encode(date1.iso8601String, forKey: .date1)
  • Related