简体   繁体   English

DateFormatter ISO8601时区

[英]DateFormatter ISO8601 TimeZones

I'm attempting to add parsing validation tests and wanted to check that the initial JSON I was sent could be turned into an object and that object in turn turned into JSON. 我正在尝试添加解析验证测试,并想检查发送给我的初始JSON是否可以变成一个对象,并且该对象又变成JSON。 In the end the validation would be that both dictionaries are equal. 最后,验证将是两个字典相等。 What I'm seeing however is that, while date parsing works, the conversion to a string replaces +00:00 with Z . 但是,我看到的是,虽然日期解析有效,但转换为字符串时将+00:00替换为Z In my research I've found that these are interchangeable and I'm aware that I could in theory replace Z with +00:00 for the comparison but I was wondering if there is a way on the ISO8601DateFormatter or any DateFormatter to say that you would prefer +00:00 over Z ? 在我的研究中,我发现它们可以互换,并且我知道我可以在理论上用+00:00代替Z进行比较,但是我想知道ISO8601DateFormatter或任何DateFormatter上是否有办法说您比Z更愿意+00:00

For those who like to see some code this is my quick playground example. 对于那些喜欢看一些代码的人,这是我的快速示例。

var date = "2018-01-30T22:13:12+00:00"
let df = ISO8601DateFormatter()
df.formatOptions = [.withInternetDateTime]

let newDate = df.date(from: date)
let newString = df.string(from: newDate!)

The ISO 8601 date format states that Z should be used when the date's timezone offset is 0. Many of the timezone date formatting symbols used with a DateFormatter also specifically result in Z if the date's timezone offset is 0. ISO 8601日期格式规定,当日期的时区偏移量为0时,应使用ZDateFormatter一起使用的许多时区日期格式符号也特别导致Z如果日期的时区偏移量为0。

If you want to generate a string from a Date and you want to ensure that you get +00:00 instead of Z , then use DateFormatter with the appropriate date formatter specifier. 如果要从Date生成一个字符串,并且要确保获取+00:00而不是Z ,请使用DateFormatter和适当的日期格式符说明符。

The format specifier xxx will give you a timezone in the format +00:00 . 格式说明符xxx将为您提供+00:00格式的时区。 XXX and ZZZZZ will also give you that same format but will give you Z in the result if the offset is 0. More on these can be seen on the Unicode Technical Specification #35 page. XXXZZZZZ也将为您提供相同的格式,但是如果偏移量为0,则结果将为Z有关更多信息,请参见Unicode技术规范#35页。

The documentation for ISO8601DateFormatter and its formatOptions states that ZZZZZ is used for the timezone. ISO8601DateFormatter及其formatOptions的文档指出ZZZZZ用于时区。 So you will always get Z for a timezone offset of 0. 因此,对于时区偏移量0,您将始终获得Z

A DateFormatter with a date format of yyyy-MM-dd'T'HH:mm:ssxxx will give you the same result you are looking for. 一个DateFormatter用的日期格式yyyy-MM-dd'T'HH:mm:ssxxx会给你你正在寻找相同的结果。 But also be sure to set the date formatter's locale to en_US_POSIX . 但也请确保将日期格式程序的语言环境设置为en_US_POSIX You will also need to ensure the output comes out in the UTC timezone. 您还需要确保输出在UTC时区输出。 Set the formatter's timeZone property to TimeZone(secondsFromGMT: 0) . 将格式程序的timeZone属性设置为TimeZone(secondsFromGMT: 0) timeZone TimeZone(secondsFromGMT: 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM