我想从字符串初始化DateFormatter().timeZone
,但是当我做类似的事情时
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.timeZone = TimeZone(abbreviation: "America/New_York")
dateFormatter.string(from: Date()) // I just get my local time printed
但是如果我这样做
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.timeZone = TimeZone(secondsFromGMT : -14400) // should be same "America/New_York"
dateFormatter.string(from: Date()) // Now I get proper New York Time
这是错误还是我做错了什么?
最佳答案
"America/New_York"
不是TimeZone
的缩写,它是一个标识符。 TimeZone(abbreviation: "America/New_York")
返回nil,因此第一个示例回退到系统的时区,这是DateFormatter
的默认值。
可以使用:
TimeZone(identifier: "America/New_York")
或以下缩写之一:
TimeZone(abbreviation: "EDT")
TimeZone(abbreviation: "EST")
纽约时区。
您还可以使用这些静态方法在
TimeZone
上打印所有已知的时区标识符和缩写:print(TimeZone.knownTimeZoneIdentifiers)
print(TimeZone.abbreviationDictionary)
关于ios - TimeZone(缩写:) vs TimeZone(secondsFromGMT :),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61399487/