-2

The back end is providing me with this date-as-a-string: 2021-09-10T12:57:01.671Z

I need to convert that string to a Date using the iOS DateFormatter; and to do so I need to set the formatter's dateFormat property.

I have tried all sorts of combinations, with no luck. Specifically I am struggling with the .671Z part.

What is the correct date format to use?

thecloud_of_unknowing
  • 1,103
  • 14
  • 23
  • "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" – Raja Kishan Sep 10 '21 at 13:46
  • 5
    `ISO8601DateFormatter` + `[.withInternetDateTime, .withFractionalSeconds]` `formatOptions` should do the trick... – Larme Sep 10 '21 at 13:48
  • 2
    @RajaKishan - No, that is not correct. The `Z` should not be in quotes. Properly configuring date formatters for ISO 8601/RFC 3339 dates is surprisingly complicated, which is why one should use `ISO8601DateFormatter`. – Rob Sep 10 '21 at 16:33
  • That format is [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). – Ole V.V. Sep 10 '21 at 18:56

1 Answers1

0

You need "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" as date format

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
     
       
guard let date = dateFormatter.date(from: self) else {
 // fallback if date is not in correct format
    return nil
}
Alastar
  • 1,284
  • 1
  • 8
  • 14
  • 3
    The `Z` should not be in quotes. If you're going to do this, I'd suggest `"yyyy-MM-dd'T'HH:mm:ss.SSSX"` and, if the formatter is also going to be used to prepare string representations for the server, set `dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)`. Frankly, as Larme said, `ISO8601DateFormatter` is the better solution. – Rob Sep 10 '21 at 16:31