2

I am working on iOS app, in which I want to call the service, for this I am using alamofire and it is really very helping me.

Now I am calling a webservice which returns me model that has codable implemented. But I have observe that it is unable to convert the Date coming from server.

SO after a lot of searching I am able to get the extension that will help me in converting the date with format. take a look at extension

   extension DateFormatter {
  static let iso8601Full: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
    formatter.calendar = Calendar(identifier: .iso8601)
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    formatter.locale = Locale(identifier: "en_US_POSIX")
    return formatter
  }()
}

and using this as :

let data = Data(json.utf8)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Full)

now take a look at the date format that is coming from server: Date Str : 2018-12-04T17:10:15.833

For me the Date format is ok and it should work but bashing my head into this matter from last day but still I do not know what is the fault. Please help me...

A.s.ALI
  • 1,992
  • 3
  • 22
  • 54
  • The format should be `"yyyy-MM-dd'T'HH:mm:ss.SSS` without the Zs. I don't see a time zone anywhere in your date string. – Sweeper Dec 05 '18 at 06:38
  • there are multiple format also, how to tackle those ? – A.s.ALI Dec 05 '18 at 06:46
  • Why would your service return multiple formats? – Sweeper Dec 05 '18 at 06:47
  • I do not know, but it has multiple format. like in one date object it has "0001-01-01T00:00:00" On this date format i am getting exception – A.s.ALI Dec 05 '18 at 06:48
  • @SharartiKAKI You can use a `.custom` date strategy to attempt multiple formats — if one works, you return the value; if none work, you can `throw`. See https://stackoverflow.com/questions/44682626/swifts-jsondecoder-with-multiple-date-formats-in-a-json-string/44686851#44686851 – Itai Ferber Dec 05 '18 at 15:46
  • That is great idea to handle this. – A.s.ALI Dec 06 '18 at 06:00

0 Answers0