将带有纪元时间和时区的时间戳字符串转换为 NSDate
- 作者: 情到深处洞自开_情仔
- 来源: 51数据库
- 2022-10-25
问题描述
我有一个以下格式的字符串
I have a String in following format
"/Date(573465600000-0800)/"
如何将其转换为常规 NSDate 对象?
How do I convert this to regular NSDate object?
推荐答案
第一部分573465600000"是Unix纪元以来的时间以毫秒为单位,第二部分-0800"是时区规范.
The first part "573465600000" is the time since the Unix epoch in milliseconds, and the second part "-0800" is a time zone specification.
这里是将JSON(日期)解析为Swift的小改动这也涵盖了时区部分:
Here is a slight modification of Parsing JSON (date) to Swift which also covers the time zone part:
extension NSDate {
convenience init?(jsonDate: String) {
let prefix = "/Date("
let suffix = ")/"
let scanner = NSScanner(string: jsonDate)
// Check prefix:
if scanner.scanString(prefix, intoString: nil) {
// Read milliseconds part:
var milliseconds : Int64 = 0
if scanner.scanLongLong(&milliseconds) {
// Milliseconds to seconds:
var timeStamp = NSTimeInterval(milliseconds)/1000.0
// Read optional timezone part:
var timeZoneOffset : Int = 0
if scanner.scanInteger(&timeZoneOffset) {
let hours = timeZoneOffset / 100
let minutes = timeZoneOffset % 100
// Adjust timestamp according to timezone:
timeStamp += NSTimeInterval(3600 * hours + 60 * minutes)
}
// Check suffix:
if scanner.scanString(suffix, intoString: nil) {
// Success! Create NSDate and return.
self.init(timeIntervalSince1970: timeStamp)
return
}
}
}
// Wrong format, return nil. (The compiler requires us to
// do an initialization first.)
self.init(timeIntervalSince1970: 0)
return nil
}
}
例子:
if let theDate = NSDate(jsonDate: "/Date(573465600000-0800)/") {
println(theDate)
} else {
println("wrong format")
}
输出:
1988-03-04 00:00:00 +0000
<小时>
Swift 3 (Xcode 8) 更新:
extension Date {
init?(jsonDate: String) {
let prefix = "/Date("
let suffix = ")/"
let scanner = Scanner(string: jsonDate)
// Check prefix:
guard scanner.scanString(prefix, into: nil) else { return nil }
// Read milliseconds part:
var milliseconds : Int64 = 0
guard scanner.scanInt64(&milliseconds) else { return nil }
// Milliseconds to seconds:
var timeStamp = TimeInterval(milliseconds)/1000.0
// Read optional timezone part:
var timeZoneOffset : Int = 0
if scanner.scanInt(&timeZoneOffset) {
let hours = timeZoneOffset / 100
let minutes = timeZoneOffset % 100
// Adjust timestamp according to timezone:
timeStamp += TimeInterval(3600 * hours + 60 * minutes)
}
// Check suffix:
guard scanner.scanString(suffix, into: nil) else { return nil }
// Success! Create NSDate and return.
self.init(timeIntervalSince1970: timeStamp)
}
}
例子:
if let theDate = Date(jsonDate: "/Date(573465600000-0800)/") {
print(theDate)
} else {
print("wrong format")
}
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
