Reputation: 941
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. 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
. 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
?
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!)
Upvotes: 0
Views: 2068
Reputation: 1809
df.formatOptions = [.withInternetDateTime, .withTimeZone, .withColonSeparatorInTimeZone]
will get you what you want.
Upvotes: 0
Reputation: 318794
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.
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.
The format specifier xxx
will give you a timezone in the format +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.
The documentation for ISO8601DateFormatter
and its formatOptions
states that ZZZZZ
is used for the timezone. So you will always get Z
for a timezone offset of 0.
A DateFormatter
with a date format of yyyy-MM-dd'T'HH:mm:ssxxx
will give you the same result you are looking for. But also be sure to set the date formatter's locale to en_US_POSIX
. You will also need to ensure the output comes out in the UTC timezone. Set the formatter's timeZone
property to TimeZone(secondsFromGMT: 0)
.
Upvotes: 3