Skip to content

Instantly share code, notes, and snippets.

@abarrak
Created February 3, 2017 12:58
Show Gist options
  • Select an option

  • Save abarrak/4ea6ccf0ba95160d9b6bf42f4aa1c491 to your computer and use it in GitHub Desktop.

Select an option

Save abarrak/4ea6ccf0ba95160d9b6bf42f4aa1c491 to your computer and use it in GitHub Desktop.
String to Date in Swift Lang
//
// Convert string to a proper formatted date type.
//
// 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment