Created
March 7, 2018 14:23
-
-
Save mbuchetics/57fdd1e4307dd5262ee5bcd073a7b32d to your computer and use it in GitHub Desktop.
Swift date parsing for date-only dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let json = | |
""" | |
{ | |
"name": "Matthias", | |
"birthday": "2017-03-22" | |
} | |
""" | |
print(json) | |
struct Person: Codable { | |
let name: String | |
let birthday: Date | |
} | |
var dayOnlyFormatter = DateFormatter() | |
dayOnlyFormatter.dateFormat = "yyyy-MM-dd" | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .formatted(dayOnlyFormatter) | |
let jsonData = json.data(using: .utf8)! | |
let person = try! decoder.decode(Person.self, from: jsonData) | |
let str = dayOnlyFormatter.string(from: person.birthday) | |
print(person.name) | |
print(person.birthday) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment