我想使用参数获取Date对象。使用时区缩写和标识符是可能的。但是我们可以使用全名时区字符串。
"dateTime": "2017-04-15T12:00:00",
"timeZone": "Pacific Standard Time"
答案 0 :(得分:0)
这当然是可能的,但不是很简单。让我们只考虑所有可能的时区,并将他们的本地化描述与您拥有的描述进行比较:
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))
}