使用SwiftyJSON将JSON date反序列化为NSDate
实例的最佳方式是什么?使用SwiftyJSON反序列化NSDate
是仅仅使用stringValue
与NSDateFormatter
还是有SwiftyJSON的内置日期API方法?
使用SwiftyJSON将JSON date反序列化为NSDate
实例的最佳方式是什么?使用SwiftyJSON反序列化NSDate
是仅仅使用stringValue
与NSDateFormatter
还是有SwiftyJSON的内置日期API方法?
这听起来像NSDate支持不内置到SwiftyJSON,但您可以扩展JSON类与您自己的便利访问器。
以下代码从this GitHub issue改编而来。
extension JSON {
public var date: NSDate? {
get {
if let str = self.string {
return JSON.jsonDateFormatter.dateFromString(str)
}
return nil
}
}
private static let jsonDateFormatter: NSDateFormatter = {
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
fmt.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return fmt
}()
}
例子:
let j = JSON(data: "{\"abc\":\"2016-04-23T02:02:16.797Z\"}".dataUsingEncoding(NSUTF8StringEncoding)!)
print(j["abc"].date) // prints Optional(2016-04-23 02:02:16 +0000)
您可能需要调整的日期格式为您自己的数据;有关更多示例,请参阅this question。另请参阅this question about date formatting in JSON。
斯威夫特3版本
extension JSON {
public var date: Date? {
get {
if let str = self.string {
return JSON.jsonDateFormatter.date(from: str)
}
return nil
}
}
private static let jsonDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
return dateFormatter
}()
}
谢谢,这看起来不错。是的,我必须调整我的日期格式。它现在不适用,例如'2016-04-24T16:47:58.319 + 0000'。不知道为什么这不会与你在答案中提到的'NSDateFormatter'格式一致。 –
由于我使用的dateFormat不接受时区信息。看看我链接的其他问题;我认为答案包括一个例子。 – jtbandes