I have a date as String but I want to convert it to Date.
The date in string looks like this – "2022-09-09T07:00:00.0000000".
Code to convert it to Date:
public static func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent
dateFormatter.timeZone = TimeZone.current
dateFormatter.setLocalizedDateFormatFromTemplate("MM-dd-yyyy HH:mm:ss")
return dateFormatter.date(from: dateString)
}
No matter what I do, I keep getting nil as the output. I tried with ISO8601 template as well and got nil. I commented out line "setLocalizedDateFormatFromTemplate" but still got nil. Can’t figure out what am I missing or doing wrong in the code.
2
Answers
First of all, this is an excellent resource. I think what you are looking for is this:
You have the year, then month, then day, then hour, minute, second, fractional seconds
Use this Snippet of code
You were not providing the proper date format