Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String to Date in Swift 2, swift 3 and swift 5

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading