Swift UTC 时区不是 UTC

Ale*_*hyn 7 xcode timezone utc gmt swift

我有一个关于 Swift 类型时区的问题。我需要获取 UTC0 时区来格式化我的 Date 对象。我正在创建这样的 TimeZone 对象。

let utcTimeZone = TimeZone(abbreviation: "UTC")

但是当创建这个对象给我 GMT0 时区。这有可能在 Swift 中获得 UTC0 时区吗?还有GMT (fixed)GMT (GMT) offset 0在操场上有什么区别?

Xcode 10.3 游乐场 在此处输入图片说明

Swe*_*per 13

从技术上讲,UTC 和 GMT 之间确实存在细微差别(GMT 可能意味着 UT1),但 API 的设计者认为它们实际上是相同的(它们是),所以他们做到了这一点:

TimeZone(identifier: "UTC") == TimeZone(identifier: "GMT")
Run Code Online (Sandbox Code Playgroud)

它们都代表一个恒定偏移量为 0 的时区。

如果您只想在某些输出文本中显示字母“UTC”,请使用DateFormatter

let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss 'UTC'"
print(formatter.string(from: Date()))
Run Code Online (Sandbox Code Playgroud)

或者更好的是,使用 a ISO8601DateFormatter,它将 a 添加Z到日期的末尾以指示日期时间是 UTC:

let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
print(formatter.string(from: Date()))
Run Code Online (Sandbox Code Playgroud)

另外,操场上的 GMT(固定)和 GMT(GMT)偏移 0 之间有什么区别?

前者来自SwiftTimeZone类,后者来自Objective-CNSTimeZone类。一个是另一个的桥接版本。从文档NSTimeZone

使用NSTimeZone时,你需要用语义或其他基金会的特定行为。