Reputation: 37
I have a JSON object that has a mySQL datetime inside of it that I need to decode in Swift and compare it to another date. How can I convert this mySQL datetime into a Swift date?
Below is what is returned in the JSON object:
{"startDate": "Sun, 02 Aug 2020 00:00:00 GMT"}
This is how we've tried to decode it:
struct jsonDate: Codable {
let startDate: String
}
let tempDate = try JSONDecoder().decode(jsonDate.self, from: data)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let previousSunday = dateFormatter.date(from: tempDate.startDate)!
Upvotes: 2
Views: 594
Reputation: 54591
You can parse your date string using DateFormatter
and setting a correct dateFormat
:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
let previousSunday = dateFormatter.date(from: tempDate.startDate)!
You can take a look at this site NSDateFormatter.com for more information.
Note
I recommend not to force-unwrap optionals:
dateFormatter.date(from: tempDate.startDate)! // crash if `nil`
and provide a default value instead or throw an error:
if let previousSunday = dateFormatter.date(from: tempDate.startDate) {
// previousSunday is valid
} else {
// throw an error etc.
}
Upvotes: 1
Reputation: 29908
Based on the string you provide for the JSON, the date format you're setting on the formatter is incorrect. The format you set matches ISO-8601-formatted strings, like
2020-02-08 00:00:00 Z
but your string would require a format like
E, dd MMM yyyy HH:mm:ss ZZZZ
instead.
Upvotes: 2