0

I'm using JSONEncoder/Codable to easily serialize an object. The object contains a Date value.

I wish to convert the Date value to unix seconds without a decimal. With any Encoder you can set the dateEncodingStrategy, however .secondsSince1970 provides a decimal, where as I'm looking for only seconds-precision. There is the option of using a custom DateFormatter, however I cannot find a dateFormat value that outputs unix seconds.

Note I know the backup option would be to completely override the encode method of the Codable struct, however I was hoping not to.

Example:

struct SomethingCodable: Codable {
  let date: Date
}

let encoder = JSONEncoder()

// Will encode to this format: 1521744936.301688
encoder.dateEncodingStrategy = .secondsSince1970

// Could use a custom DateFormatter?? Wish for: 1521744936
encoder.formatted(aDateFormatter)
mm282
  • 453
  • 3
  • 7

1 Answers1

1

Answer is this:

jsonEncoder.dateEncodingStrategy = .custom({ (date, encoder) throws in
    var container = encoder.singleValueContainer()
    let seconds: UInt = UInt(date.timeIntervalSince1970)
    try container.encode(seconds)
})
mm282
  • 453
  • 3
  • 7
  • 2
    You should use `Int` instead of `UInt` for seconds. Or any timestamp that is before 1970 would likely crash. – zhubofei Jan 25 '19 at 20:32