首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TimeZone(缩写:) vs TimeZone(secondsFromGMT:)

TimeZone(缩写:) vs TimeZone(secondsFromGMT:)
EN

Stack Overflow用户
提问于 2020-04-24 09:13:22
回答 1查看 64关注 0票数 1

我想从一个字符串初始化一个DateFormatter().timeZone,但是当我这样做的时候

代码语言:javascript
复制
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.timeZone = TimeZone(abbreviation: "America/New_York")
dateFormatter.string(from: Date()) // I just get my local time printed

但如果我这么做了

代码语言:javascript
复制
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

这是一个bug,还是我没有做对什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-24 09:26:34

"America/New_York"不是TimeZone的缩写-它是一个标识符。TimeZone(abbreviation: "America/New_York")返回nil,因此第一个示例返回到系统的时区,这是DateFormatter的默认时区。

使用以下两种方法:

代码语言:javascript
复制
TimeZone(identifier: "America/New_York")

或者这些缩写之一:

代码语言:javascript
复制
TimeZone(abbreviation: "EDT")
TimeZone(abbreviation: "EST")

纽约时区。

您还可以在TimeZone上使用这些静态方法打印所有已知的时区标识符和缩写

代码语言:javascript
复制
print(TimeZone.knownTimeZoneIdentifiers)
print(TimeZone.abbreviationDictionary)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61399487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档