-3

I've tried using a DateFormatter() to format a string (from C# DateTime) into a Swift Date(). However, I keep getting nil.

Here is the code I've been playing around with:

let dateAndTimeString = "2021-08-24T10:16:06.647" //Copied from a C# API

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" //Also trying without this dateFormat returns nil

let date = dateFormatter.date(from: dateAndTimeString) //Returns nil

If anyone could help point me in the right direction, that would be great!

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Matt Ward
  • 1,095
  • 1
  • 14
  • 28

1 Answers1

1

The dateFormat you used is not matched with the given date string. The correct dateFormat should be below

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
SamB
  • 1,560
  • 1
  • 13
  • 19
  • 1
    This works beautifully, thanks! – Matt Ward Aug 24 '21 at 10:42
  • 1
    This would still have some issues and it might fail if the user's device 12-24 hour settings is set to 12h. Check the correct approach at the duplicated SO [post](https://stackoverflow.com/a/28016692/2303865) – Leo Dabus Aug 24 '21 at 15:50