Я пытаюсь отформатировать дату в документе JSON в формате «мм-дд-гггг».У меня есть следующие данные:
{"data":[{
"id": 123,
"url": "https://www.google.com",
"title": "The Google link",
"created_at": "2017-08-29T04:00:00.000Z",//date to format
"sent": true,
"alternative": "https://google.com",
"things": [],
"description": [
"search",
"lookup"
],
"company": "Alphabet"
}]}
Это моя структура:
struct Sitedata: Decodable{
let data: [site]
}
struct site: Decodable {
let id: Int
let url: String
let title: String
let created_at: String
let sent: Bool
let alternative: String
let things: [String]
let description: [String]
let company: String
}
let sites = try JSONDecoder().decode(Sitedata.self, from: data)
Я попробовал следующий метод, но он выдал nil
:
func date(dateString: String){
// var dateString = "14.01.2017T14:54:00"
let format = "dd.MM.yyyy'T'HH:mm:ss"
let date = Date()
print("original String with date: \(dateString)")
print("date String() to Date(): \(dateString.toDate(format: format)!)")
print("date String() to formated date String(): \(dateString.toDateString(inputFormat: format, outputFormat: "dd MMMM")!)")
print("format Date(): \(date.toString(format: "dd MMM HH:mm")!)")
}
extension DateFormatter {
convenience init (format: String) {
self.init()
dateFormat = format
locale = Locale.current
}
}
extension String {
func toDate (format: String) -> Date? {
return DateFormatter(format: format).date(from: self)
}
func toDateString (inputFormat: String, outputFormat:String) -> String? {
if let date = toDate(format: inputFormat) {
return DateFormatter(format: outputFormat).string(from: date)
}
return nil
}
}
extension Date {
func toString (format:String) -> String? {
return DateFormatter(format: format).string(from: self)
}
}
How would I be able to parse and then format this date to MM-dd-yyyy?