0

I have Swift 5 and such date string:

let dateString = "2019-11-09T08:14:09.361404Z"

and two approaches to convert it to date:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"
let date = dateFormatter.date(from: dateString)
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withFractionalSeconds, .withInternetDateTime]
let date = dateFormatter.date(from: dateString)

as result:

first case: 2019-11-09 05:14:09 +0000

second case: 2019-11-09 08:14:09 +0000

Dates differ by 3 hours (just like my timezone differs from GMT). Setting the timezone to my current both formatters doesn't affect the results.

Could you please explain difference and which result is correct?

Maxim
  • 33
  • 6
  • `DateFormatter` and `ISO8601DateFormatter` use different time zones by default. See the duplicate for more info. Also note that the "Z" in your string actually means an offset of 0, rather than literally 'Z', so parsing it as `'Z'` is incorrect. – Sweeper Aug 12 '22 at 10:21
  • Thanks for answer! It's good point about parsing of 'Z'. But about different time zones - I've set current time zones to both formatters and result was the same. – Maxim Aug 12 '22 at 10:47
  • Did you also fix the `'Z'`? Because if you didn't, `ISO8601DateFormatter` will understand the `Z` correctly and `DateFormatter` won't. So `ISO8601DateFormatter` will not use the default time zone you gave it, but `DateFormatter` - they are still using different time zones at the end of the day. I have added a better duplicate with answers that shows you how to use `DateFormatter` to parse the `Z`. – Sweeper Aug 12 '22 at 10:58
  • mmm...got it, I have to set the timezone to be the same as the date. – Maxim Aug 12 '22 at 11:01
  • No, I just chose ISO8601DateFormatter but it would be great to know how to fix Z :) I have to see your duplicate, thank you! – Maxim Aug 12 '22 at 11:06

0 Answers0