【问题标题】:Use SwiftyJSON to deserialize NSDate使用 SwiftyJSON 反序列化 NSDate
【发布时间】:2016-04-23 01:40:40
【问题描述】:

使用 SwiftyJSON 将 JSON date 反序列化为 NSDate 实例的最佳方法是什么?

是仅使用 stringValueNSDateFormatter 还是使用 SwiftyJSON 的内置日期 API 方法?

【问题讨论】:

    标签: json swift nsdate swifty-json


    【解决方案1】:

    听起来 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

    【讨论】:

    • 谢谢,这看起来很棒。是的,我必须调整我的日期格式。它现在不适用于2016-04-24T16:47:58.319+0000 的示例日期。不知道为什么这不符合您在答案中提到的NSDateFormatter 格式。
    • 因为我使用的 dateFormat 不接受时区信息。看看我链接的其他问题;我认为答案包括一个例子。
    【解决方案2】:

    Swift 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
        }()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2021-12-08
      • 2015-11-22
      相关资源
      最近更新 更多