gpt4 book ai didi

swift - 使用全名时区在 Swift 中获取 Date 对象?

转载 作者:行者123 更新时间:2023-11-30 11:38:29 27 4
gpt4 key购买 nike

我想使用参数获取 Date 对象。使用时区缩写和标识符是可能的。但是我们可以得到全名时区字符串吗?

"dateTime": "2017-04-15T12:00:00",
"timeZone": "Pacific Standard Time"

最佳答案

这当然是可能的,但不是很简单。让我们获取所有可能的时区,并将其本地化描述与您拥有的描述进行比较:

let dateString = "2017-04-15T12:00:00"
let timeZoneName = "Pacific Standard Time"
let locale = Locale(identifier: "en-US")

let knownTimeZones = TimeZone.knownTimeZoneIdentifiers.flatMap { TimeZone(identifier: $0) }
let timeZone = knownTimeZones.first {
// I don't know what type of name you have, `.standard` does not have to be correct
$0.localizedName(for: .standard, locale: locale) == timeZoneName
}

print(timeZone)

if let timeZone = timeZone {
let dateFormatter = DateFormatter()
dateFormatter.locale = locale
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = timeZone

print(dateFormatter.date(from: dateString))
}

关于swift - 使用全名时区在 Swift 中获取 Date 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49474678/

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