0

I have a date (timestamp) passing through my JSON data that is not in iso8601 format. So, when I try to parse it I get a fatal error. I think I need to use some type of date formatting protocol but I am not sure. If you have dealt with this is the past, then please help. Thanks.

let json = """

{
    "customers":[
        {
            "firstName" : "John",
            "lastName" : "Smith",
            "dateCreated" : "01/01/2019",
            "address" : {
                "street" : "1 street",
                "city" : "myCity",
                "state" : "myState",

            }
        }

    ]

}
  • 3
    Possible duplicate of [Swift formatting JSON date](https://stackoverflow.com/questions/53577394/swift-formatting-json-date) – jscs Mar 14 '19 at 16:23

1 Answers1

-1

Perhaps, this Extension will work for you. Be sure to reference it in your code as well. Good luck.

extension DateFormatter {
    static let iso8601 : DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()
}


let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601)
  • 1
    Why would you call that "full"? – jscs Mar 14 '19 at 16:31
  • 1
    Don't forget to set the date formatter locale to "en_US_POSIX" when parsing fixed date formats. Btw how can you tell OP date format is `"MM/dd/yyy"` and not `"dd/MM/yyy"` and you should use `y` or `yyyy` not `yyy` – Leo Dabus Mar 14 '19 at 17:20
  • 1
    If you don't set the locale the parsing might fail depending on the users device locale and settings – Leo Dabus Mar 14 '19 at 17:58