使用全名时区获取 Swift 中的日期对象?

Getting Date object in Swift using full name timezone?

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

"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: [=10=]) }
let timeZone = knownTimeZones.first {
     // I don't know what type of name you have, `.standard` does not have to be correct
     [=10=].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))
}