DAY #34

Codable (Part 4 of 4)

Working with codable dates

There are many ways to represent a date in CS. With codable, you can code and convert date representations to match the Date() type in swift.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//Decoding example. Convert an ISO8601 to Date()
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

//Custom: You can also decode from a custom date format using DateFormatter().
decoder.dateDecodingStrategy = .formatted(someCustomDateFormatter)

//You can also decode with a closure
decoder.dateDecodingStrategy = .custom { decoder in
  //...
  return ...
}

Originally published 09/19/2021 @ https://pittcsc.org/ Discord

Published here on 09/09/2022. Blog published date reflects the original date of publication.