I have strings like this 2020-09-21T21:13:55.636Z
... I want to convert them into Date
s and here's what I do;
func convertToDate(str: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return dateFormatter.date(from: str)!
}
The above code crashes on the unwrapping. I'm guessing it's because of the format... Any idea what I'm doing wrong?
For that date string you should use ISO8601DateFormatter
, like this:
var str = "2020-09-21T21:13:55.636Z"
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let date = formatter.date(from: str)
That will save you the trouble of trying to get a format string exactly right.