How can I convert a string to Date in Swift 2, swift 3 and swift 5?
I am going to convert a string to Date in Swift 2, swift 3 and swift5. Can you please help me?
>Solution :
// Swift 3.0
private func stringToDate(dateString: String?) -> Date? {
if let str = dateString {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd, yyyy h:mm a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
return formatter.date(from: str)
} else {
return nil
}
}
// Swift 2
private func stringToDate(dateString: String?) -> NSDate? {
if let str = dateString {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM dd, yyyy h:mm a"
formatter.AMSymbol = "AM"
formatter.PMSymbol = "PM"
return formatter.dateFromString(str)
} else {
return nil
}
}