0

I have a string form 2019-06-22T01:11:08.996Z but I can't work out why my date formatter won't convert it to an NSDate object. I have tried using yyyy-MM-dd'T'HH:mm:ssZ. But I always get nil.

What would be the correct format for form date as above?

KBell
  • 502
  • 8
  • 23
Daniel
  • 355
  • 2
  • 3
  • 15

1 Answers1

1

Try following code to get the date:

    let dateStr = "2019-06-22T01:11:08.996Z"
    let date = dateFrom(dateString: dateStr, withDateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", andLocale: "en_US_POSIX")
    print(date)

--

func dateFrom(dateString: String, withDateFormat dateFormat: String, andLocale locale: String) -> Date? {
    let dateformatter = DateFormatter()
    dateformatter.locale = Locale(identifier: locale)
    dateformatter.dateFormat = dateFormat
    return dateformatter.date(from: dateString)
}
Bhavik Modi
  • 1,517
  • 14
  • 29
  • 2
    1. Wrong date format. 2. Wrong locale. 3. Don't use `NSLocale`, use `Locale`. 4. Don't force-unwrap the result. The return type should be `Date?`, not `Date!`. – rmaddy Jun 26 '19 at 04:36
  • 1
    Still need to fix the locale. You need `en_US_POSIX`. – rmaddy Jun 26 '19 at 05:07