我想将时区显示为“IST”,“EST”等。 这似乎很简单,但有一个问题。当我使用以下代码时:
let timeZone = TimeZone.current.abbreviation()
对于印度,我得到“格林威治标准时间+5:30”,但对于多伦多,我得到“EDT”。 请帮助,或让我知道其他一些显示此类缩写的方法。
编辑1
我想出了一个解决方法,但有时我会得到一些奇怪的时区:
func getTimeZoneAbbrevation() -> String {
var returnTimeZone = ""
let timezone = TimeZone.current.identifier
let dict = TimeZone.abbreviationDictionary
for (key,value) in dict {
if value == timezone {
returnTimeZone = key
break
}
}
if returnTimeZone == "" {
if let timezone = NSTimeZone.default.abbreviation() {
returnTimeZone = timezone
}
}
return returnTimeZone
}
答案 0 :(得分:0)
这应该有用。
let someTime = TimeZone(identifier: "America/Toronto")
let timezone = someTime?.abbreviation()
现在timezone
包含值"EDT"
,因此您可以直接使用它。
仅供参考,如果您想检查这些标识符,以便从
获取var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
我希望这会有所帮助。
答案 1 :(得分:0)
试试这个
让timeZoneDict = TimeZone.abbreviationDictionary.filter {
$ 0.value == TimeZone.current.identifier
}
if!timeZoneDict.isEmpty {
让timeZone = timeZoneDict.first?.key
打印(的timeZone)
}