DEV Community

Liang Wang
Liang Wang

Posted on

DateDecodingStrategy

Example date: "2014-11-24T05:52:18-00:00"
Question: how to decode it into Date type?

Each user registered has a very specific format: 2015-11-10T01:47:18-00:00. This is known as ISO-8601, and is so common that there’s a built-in dateDecodingStrategy called .iso8601 that decodes it automatically.

Solution:
In the URLSession part to decode data, define the decoder to use this dateDecodingStrategy like this:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
Enter fullscreen mode Exit fullscreen mode

then return the decode data:

return try decoder.decode([T].self, from: data)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)