gpt4 book ai didi

ios - 如何将 Date(1440156888750-0700) 这样的日期转换为 Swift 可以处理的东西?

转载 作者:行者123 更新时间:2023-11-30 10:44:09 24 4
gpt4 key购买 nike

所以在我的应用程序中,我需要处理像 \/Date(1440156888750-0700)\/ 这样的日期,我认为第一部分代表 1970 年 1 月 1 日的秒数,第二部分代表 1970 年 1 月 1 日的秒数部分是时区。我不知道如何使用 Swift 2 在 Xcode 7 中处理这样的数据并以我们都理解的方式显示它?

最佳答案

(这个答案的前一个版本实际上是错误的,它没有正确处理时区。)

根据Stand-Alone JSON Serialization :

DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

Use JSON.NET to parse json date of format Date(epochTime-offset)

... In this [screwy format][1], the timestamp portion is still based solely on UTC. The offset is extra information. It doesn't change the timestamp. You can give a different offset, or omit it entirely and it's still the same moment in time.

\/Date(1440156888750-0700)\/中的第一个数字是自格林尼治标准时间 1970 年 1 月 1 日“纪元”以来的毫秒数以及时间区域部分 -0700 必须被忽略。

这里是 DateSwift 5 扩展方法,用于检查正则表达式字符串的有效性(接受 \/Date(...)\//Date(...)/,有或没有时区规范)并转换给定的数量毫秒到日期:

extension Date {
init?(jsonDate: String) {

let pattern = #"\\?/Date\((\d+)([+-]\d{4})?\)\\?/"#
let regex = try! NSRegularExpression(pattern: pattern)
guard let match = regex.firstMatch(in: jsonDate, range: NSRange(jsonDate.startIndex..., in: jsonDate)) else {
return nil
}

// Extract milliseconds:
let dateString = jsonDate[Range(match.range(at: 1), in: jsonDate)!]
// Convert to UNIX timestamp in seconds:
let timeStamp = Double(dateString)! / 1000.0
// Create Date from timestamp:
self.init(timeIntervalSince1970: timeStamp)
}
}

示例:

let jsonDate = "\\/Date(1440156888750-0700)\\/"
print("JSON Date:", jsonDate)

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

输出:

JSON Date: \/Date(1440156888750-0700)\/Date: 2015-08-21 11:34:48 +0000

(Swift 3 和 Swift 4 的版本可以在编辑历史记录中找到。)

关于ios - 如何将 Date(1440156888750-0700) 这样的日期转换为 Swift 可以处理的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157165/

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