将JSON(日期)解析为Swift [英] Parsing JSON (date) to Swift

查看:150
本文介绍了将JSON(日期)解析为Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift中的应用程序中返回了JSON,并且有一个字段可以返回给我一个日期。当我参考这些数据时,代码给了我类似/ Date(1420420409680)/的内容。如何将其转换为NSDate?在Swift中,我已经使用Objective-C测试了示例,但没有成功。

I have a return JSON in my application in Swift, and have a field that returns me a date. When I refer to this data, the code gives me something like "/ Date (1420420409680) /". How do I convert this into NSDate? In Swift, please, I´ve tested examples with Objective-C, without success.

推荐答案

这看起来与JSON非常相似编码Microsoft的ASP.NET AJAX使用的日期,其中
JavaScript和.NET中的JavaScript对象表示法(JSON)简介

That looks very similar to the JSON encoding for a date as used by Microsoft's ASP.NET AJAX, which is described in An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET:


例如,Microsoft的ASP .NET AJAX既不使用所描述的
约定。相反,它将.NET DateTime值编码为JSON字符串,
其中字符串的内容为/ Date(ticks)/,其中ticks
表示自纪元(UTC)以来的毫秒数。所以1989年11月29日,
4:55:30 AM,UTC编码为\ / Date(628318530718)\ /\".

For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".

唯一的区别是您的格式为 /日期(刻度)/
而不是 \ / Date(ticks)\ /

The only difference is that you have the format /Date(ticks)/ and not \/Date(ticks)\/.

您必须提取括号之间的数字。将其除以1000
得出自1970年1月1日以来的秒数。

You have to extract the number between the parentheses. Dividing that by 1000 gives the number in seconds since 1 January 1970.

以下代码显示了如何做到这一点。对于 NSDate ,它实现为
afailable convenience initializer:

The following code shows how that could be done. It is implemented as a "failable convenience initializer" for NSDate:

extension NSDate {
    convenience init?(jsonDate: String) {

        let prefix = "/Date("
        let suffix = ")/"
        // Check for correct format:
        if jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) {
            // Extract the number as a string:
            let from = jsonDate.startIndex.advancedBy(prefix.characters.count)
            let to = jsonDate.endIndex.advancedBy(-suffix.characters.count)
            // Convert milliseconds to double
            guard let milliSeconds = Double(jsonDate[from ..< to]) else {
                return nil
            }
            // Create NSDate with this UNIX timestamp
            self.init(timeIntervalSince1970: milliSeconds/1000.0)
        } else {
            return nil
        }
    }
}

示例用法(包含日期字符串):

Example usage (with your date string):

if let theDate = NSDate(jsonDate: "/Date(1420420409680)/") {
    print(theDate)
} else {
    print("wrong format")
}

这给出了输出


2015-01-05 01:13:29 +0000






Swift 3更新(Xcode 8):

extension Date {
    init?(jsonDate: String) {

        let prefix = "/Date("
        let suffix = ")/"

        // Check for correct format:
        guard jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) else { return nil }

        // Extract the number as a string:
        let from = jsonDate.index(jsonDate.startIndex, offsetBy: prefix.characters.count)
        let to = jsonDate.index(jsonDate.endIndex, offsetBy: -suffix.characters.count)

        // Convert milliseconds to double
        guard let milliSeconds = Double(jsonDate[from ..< to]) else { return nil }

        // Create NSDate with this UNIX timestamp
        self.init(timeIntervalSince1970: milliSeconds/1000.0)
    }
}

示例:

if let theDate = Date(jsonDate: "/Date(1420420409680)/") {
    print(theDate)
} else {
    print("wrong format")
}

这篇关于将JSON(日期)解析为Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆