簡體   English   中英

使用Swift Decodable解析任意格式的JSON日期

[英]Parsing arbitrary format JSON date with Swift Decodable

我正在嘗試將JSON文檔中的日期格式化為“ mm-dd-yyyy”格式。 我有以下數據:

{"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?

首先,按照雨燕命名約定: UpperCamelCase類名和lowerCamelCase變量名。 其次,幫自己一個忙,並在Date字段中創建created_at ,這很明顯。 以后您可以省下很多頭痛。

這是代碼:

struct SiteData: Decodable{
    let data: [Site]
}

struct Site: Decodable {
    let id: Int
    let url: String
    let title: String
    let created_at: Date        // changed to Date
    let sent: Bool
    let alternative: String
    let things: [String]
    let description: [String]
    let company: String
}

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let sites = try decoder.decode(SiteData.self, from: json)

現在已經從JSON作為正確的Date解析了created_at ,您可以根據需要設置其格式:

let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
print(formatter2.string(from: sites.data[0].created_at))

請注意, DateFormatter創建成本非常高,更改其dateFormat屬性的成本甚至更高。 如果必須將大量日期格式化為字符串(反之亦然),則只需創建一次日期格式化程序,然后繼續重復使用它們即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM