我想将1529704800000转换为Date对象,但是我没有得到正确的日期。我从json中获取价值。我正在以这种方式转换值:
class Example: Decodable {
var id: Int64?
var date: Date?
init(json: [String: Any]) {
id = json["id"] as? Int64 ?? -1
var dateTime = (json["date"] as AnyObject? as? Int64) ?? 0
date = Date(timeIntervalSince1970: (TimeInterval(dateTime / 1000)))
}
static func fetchReportsForUser(authorId: Int64) -> [Report]? {
let urlString = "http://localhost:8080/test-application/rest/example/"
let url = URL(string: urlString)!
var examples = [Example]()
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .default).async {
URLSession.shared.dataTask(with: url) { (data, response, error) -> Void in
if error != nil {
print(error!)
return
}
guard let data = data else {
return
}
if(data.isEmpty) {
group.leave()
return
}
do {
examples = try JSONDecoder().decode([Example].self, from: data)
} catch let err {
print(err)
}
group.leave()
}.resume()
}
group.wait()
return examples
}
}
当我这样做时,我仍然会得到50472-09-04 16:00:00 +0000作为日期。我使用Double而不是Int64进行了尝试,但是得到了相同的结果。
答案 0 :(得分:3)
只需使用适当的日期解码策略
JSONDecoder
注意:不要使异步任务同步。学习了解异步数据处理并使用完成处理程序。
答案 1 :(得分:2)
您的整数似乎代表毫秒而不是秒,这给了未来数千年的日期!
将其除以1000(除去最后3个零)得出的UTC时间为2018年6月22日晚上10点。
此外,尝试更改从json
投射到日期的行:
if let dateTime = json["date"] as? Int {
date = Date(timeIntervalSince1970: dateTime/1000)
}