-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
  • 35,353
  • 5
  • 20
  • 45
Matt Ward
  • 913
  • 1
  • 13
  • 24

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,284
  • 1
  • 11
  • 18
  • 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