gpt4 book ai didi

swift - 将带有纪元时间和时区的时间戳字符串转换为 NSDate

转载 作者:搜寻专家 更新时间:2023-10-31 21:51:12 25 4
gpt4 key购买 nike

我有一个格式如下的字符串

"/Date(573465600000-0800)/"

如何将其转换为常规 NSDate 对象?

最佳答案

第一部分“573465600000”是自Unix纪元以来的时间以毫秒为单位,第二部分“-0800”是时区规范。

这里是对 Parsing JSON (date) to Swift 的轻微修改这也涵盖了时区部分:

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")
}

关于swift - 将带有纪元时间和时区的时间戳字符串转换为 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28854066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com