Your date string is wrong: do not include ' before and after T
This works:
let birth = "1991-03-24T00:00:00"
func convertStringToDate(dateString : String) -> Date {
let dateFormatter : DateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "UTC") // Need to define TimeZone
if let date = dateFormatter.date(from: dateString) { // No parenthesis needed here around dateString
return date
}
return Date()
}
let birthDate = convertStringToDate(dateString: birth)
print("birthDate", birthDate)
.
And gives:
birthDate 1991-03-24 00:00:00 +0000
Notes:
- labels as DateString should start with lowercase
- You need to define TimeZone, otherwise you may get a different result depending on your locale
If you get the String with single quoted T,
let birth = "1991-03-24'T'00:00:00"
you have 2 options:
var birth = "1991-03-24'T'00:00:00"
birth = birth.replacingOccurrences(of: "'", with: "")
- change the dateFormat, by adding single quote (ned to escape it, hence '' before and after 'T' as:
dateFormatter.dateFormat = "yyyy-MM-dd'''T'''HH:mm:ss"