这看起来与 Microsoft 的 ASP.NET AJAX 使用的日期的 JSON 编码非常相似,后者
描述在An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET:
例如,Microsoft 的 ASP.NET AJAX 既不使用上述描述的
公约。相反,它将 .NET DateTime 值编码为 JSON 字符串,
其中字符串的内容是 /Date(ticks)/ 并且在哪里打勾
表示自纪元 (UTC) 以来的毫秒数。所以在 1989 年 11 月 29 日,
凌晨 4:55:30,UTC 编码为“\/Date(628318530718)\/”。
唯一的区别是你的格式是/Date(ticks)/
而不是\/Date(ticks)\/。
您必须提取括号之间的数字。除以 1000
给出自 1970 年 1 月 1 日以来的秒数。
以下代码显示了如何做到这一点。它被实现为
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
}
}
}
示例用法(使用您的日期字符串):
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")
}