ios - TimeZone(缩写:) vs TimeZone(secondsFromGMT :)

标签 ios swift

我想从字符串初始化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/

相关文章:

ios - Xcode调试器在集成Fabrics iOS SDK时不显示变量的值

ios - 使用实例填充 UITableview 来填充数组

ios - 如何在 swift 中使用 IGListKit 创建一个两列的 Collection View 列表

ios - 无法识别 ReachabilityManager 单例类方法

ios - 在父 UIViewController UIView 中以模态方式呈现 ViewController

ios - 无法在 iOS 12 上使用 SwiftyJSON 构建项目

ios - UITableView 中 UINavigationBar 的高度不变

iOS自定义对象初始化错误

ios - 我想在我的库文件中调用 APNS 设备 token

objective-c - 如何从我的 appDelegate 访问我的 viewController? ( swift )