mbuchetics
3/7/2018 - 2:23 PM

Swift date parsing for date-only dates

Swift date parsing for date-only dates

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)