我有一个使用JSONDecoder()解析的json文件。但是,我收到了iso-8601格式的日期类型的可变时间戳记(“yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX”),但是在我看来,我想以自定义格式显示它: “dd / mm / yy HH:mm:ss”。
我已经编写了以下代码,但是时间戳为nil,并且我认为当时间戳以iso-8601格式出现时,“date”不是正确的类型:
错误json:typeMismatch(Swift.Double,
Swift.DecodingError.Context(codingPath:[_JSONKey(stringValue:“索引
0“,intValue:0),CodingKeys(stringValue:” timestamp“,intValue:
nil)],debugDescription:“预期对Double进行解码,但发现
字符串/数据。”,underlyingError:nil))
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
}
}
最佳答案
当您解码Date
时,解码器默认需要UNIX时间戳(一个Double
),这就是错误消息告诉您的内容。
但是,如果添加Date
,则确实可以将ISO8601字符串解码为decoder.dateDecodingStrategy = .iso8601
,但这仅解码标准ISO8601字符串,而没有毫秒。
有两种选择:
formatted
添加一个dateDecodingStrategy
DateFormatter
。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(...
timestamp
为let timestamp: String
并使用
dateString
中的两个格式化程序或两个日期格式来回转换字符串。 关于ios - 将日期格式iso-8601更改为自定义格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52128883/