BetterCodable icon indicating copy to clipboard operation
BetterCodable copied to clipboard

JSONEncoder's `dateEncodingStrategy` ignored for default `Date`

Open Jeehut opened this issue 4 years ago • 0 comments

I'm using a JSONEncoder with dateEncodingStrategy set to .iso8601 like this:

extension JSONEncoder {
  public static var iso: JSONEncoder {
    let encoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    return encoder
  }
}

My Codable type has a discoverDate property which I specify as @DefaultCodable:

@DefaultCodable<Date.DefaultToNow>
public var discoverDate: Date

The DefaultCodableStrategy I use is defined like this (I'm using Date() as the default value):

extension Date {
  public enum DefaultToNow: DefaultCodableStrategy {
    public static var defaultValue: Date { Date() }
  }
}

But for some reason, when I encode the object using JSONEncoder.iso, it ignores the dateEncodingStrategy which I set to iso8601 but it renders like I didn't set it. For example, my JSON output looks something like this:

{ "discoverDate" : 7200 }

But I would expect it to look like this:

{ "discoverDate" : "2001-01-01T02:00:00Z" }

I believe this is a bug. Any ideas how I can work around this?

Jeehut avatar Sep 13 '21 05:09 Jeehut