解释
TimeZone(secondsFromGMT: 0)
代表 相对于格林威治时间 (GMT) 偏移 0 秒,也就是 UTC 时区。
举例
let date = Date() // 假设现在是北京时间 18:00 (GMT+8)
// 默认情况下,格式化器会用本地时区 (GMT+8)
let localFormatter = DateFormatter()
localFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(localFormatter.string(from: date))
// 输出: 2025-09-17 18:00:00
// 如果强制用 UTC (GMT+0)
let utcFormatter = DateFormatter()
utcFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
utcFormatter.timeZone = TimeZone(secondsFromGMT: 0)
print(utcFormatter.string(from: date))
// 输出: 2025-09-17 10:00:00
你会发现,同一个 Date
,在本地时区是 18:00,但在 UTC 时区会显示 10:00。