Skip to content

Instantly share code, notes, and snippets.

@backslash-f
Last active September 10, 2020 04:05
Show Gist options
  • Save backslash-f/637f8484bf70758354f838408aa35aa9 to your computer and use it in GitHub Desktop.
Save backslash-f/637f8484bf70758354f838408aa35aa9 to your computer and use it in GitHub Desktop.
Swift Codable + Date
// Fix for error: "Expected to decode Double but found a string/data instead"
public struct CodableEntity: Codable {
public let myBool: Bool
public let myDate: Date
public let myInt: Int
}
let jsonData = Data("""
{
"myBool": true,
"myDate": "2018-12-12",
"myInt": 4
}
""".utf8)
// This bitch here.
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let myCodableEntity = try! decoder.decode(CodableEntity.self, from: jsonData)
// GMT Example
extension Date {
/// Returns a `Date` in `GMT` format, that is: "yyyy-MM-dd HH:mm:ss VV" and `TimeZone(secondsFromGMT: 0)`.
///
/// - Parameter givenDate: If informed and in the expected format ("yyyy-MM-dd HH:mm:ss VV"), tries to initialize
/// a `Date` object with it and then return as GMT.
/// - Returns: `Date` object in `GMT` format
func asGMT(fromDate givenDate: String = "") -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let dateString = givenDate.isEmpty ? formatter.string(from: self) : givenDate
return formatter.date(from: dateString)
}
}
@zappycode
Copy link

//This bitch here

Maybe one of the greatest comments I've ever seen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment