Swift:如何让ISO8601DateFormatter输出GMT日期时显示+00:00而非Z
解决ISO8601DateFormatter在GMT时区显示Z而非+00:00的问题
你遇到的问题是ISO8601DateFormatter的默认行为导致的:当时区偏移为0时,它会遵循ISO 8601标准用Z代替+00:00,而.withTimeZone选项无法修改这个规则。要强制显示+00:00格式,你可以改用DateFormatter并指定精确的格式字符串。
解决方案代码
let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: "Europe/London") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" dateFormatter.locale = Locale(identifier: "en_US_POSIX") // 避免区域设置干扰格式 // 测试输出 let bstDate = Date(timeIntervalSince1970: 1697436000) print(dateFormatter.string(from: bstDate)) // 2023-10-16T10:00:00+01:00 let gmtDate = Date(timeIntervalSince1970: 1698885779) print(dateFormatter.string(from: gmtDate)) // 2023-11-01T20:42:59+00:00
关键说明
ZZZZZ格式符会强制以±HH:mm的形式显示所有时区偏移,包括00:00,完全替代Z的输出。- 设置
locale为en_US_POSIX是必要的,确保格式不受系统区域设置影响,输出结果稳定一致。
内容的提问来源于stack exchange,提问作者Gavin
相关产品推荐
相关产品推荐

