【问题标题】:change date format iso-8601 to custom format将日期格式 iso-8601 更改为自定义格式
【发布时间】:2019-02-07 06:41:51
【问题描述】:

我有一个使用 JSONDecoder() 解析的 json 文件。但是,我收到了日期类型为 iso-8601 格式的变量时间戳(“yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX”),但在我看来,我想以自定义格式显示它: "dd/mm/yy HH:mm:ss"。

我编写了以下代码,但我得到的时间戳为零,此外,我认为当时间戳采用 iso-8601 格式时,“日期”不是正确的类型:

错误 json: typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "索引 0", intValue: 0), CodingKeys(stringValue: "timestamp", intValue: nil)], debugDescription: "预期解码 Double 但发现 字符串/数据。”,基础错误:无))

swift4

import UIKit

enum Type : String, Codable {
    case organizational, planning
}

// structure from json file
struct News: Codable{
    let type: Type
    let timestamp: Date //comes in json with ISO-8601-format
    let title: String
    let message: String

    enum  CodingKeys: String, CodingKey { case type, timestamp, title, message}

    let dateFormatter : DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yy HH:mm:ss"  // change format ISO-8601 to dd/MM/yy HH:mm:ss
        return formatter
    }()

    var dateString : String {
        return dateFormatter.string(from:timestamp) // take timestamp variable of type date and make it a string -> lable.text
    }
}

【问题讨论】:

    标签: ios swift4 dateformatter jsondecoder


    【解决方案1】:

    当您解码 Date 时,解码器默认需要一个 UNIX 时间戳(Double),这就是错误消息告诉您的内容。

    但是,如果您添加 decoder.dateDecodingStrategy = .iso8601,您确实可以将 ISO8601 字符串解码为 Date,但这仅解码标准 ISO8601 字符串没有毫秒。

    有两种选择:

    1. 添加formatted dateDecodingStrategyDateFormatter

      let dateFormatter = DateFormatter()
      dateFormatter.locale = Locale(identifier: "en_US_POSIX")
      dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
      let decoder = JSONDecoder() 
      decoder.dateDecodingStrategy = .formatted(dateFormatter)
      try decoder.decode(...
      
    2. 声明timestamp

      let timestamp: String
      

      并使用dateString 中的两个格式化程序或两种日期格式来回转换字符串。

    【讨论】:

    • 感谢您的帮助!你能告诉我在哪里添加你的解决方案 1) 吗?我把它放入“let dateFormatter : DateFormatter = {..”,但它仍然不起作用。我认为我执行错了......
    • 就在decode 行之前。我更新了答案。
    • 像魅力一样工作!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2013-05-22
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多