Skip to content

Instantly share code, notes, and snippets.

@drosenstark
Last active August 29, 2015 14:24
Show Gist options
  • Save drosenstark/89b0337e9f91314458f6 to your computer and use it in GitHub Desktop.
Save drosenstark/89b0337e9f91314458f6 to your computer and use it in GitHub Desktop.
NSDate to String, String to Date in Swift
// this could be a global formatter available to these other two
let formatter = NSDateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ";
// since we lose something going to string and back, this does both passes for the current date/time
func now() -> NSDate {
return stringToDate(dateToString(NSDate()))
}
func dateToString(date:NSDate) -> String {
return formatter.stringFromDate(date);
}
func stringToDate(date:String) -> NSDate {
return formatter.dateFromString(date) ?? NSDate()
}
// test it out
let date = now()
let dateAsString = dateToString(date)
let dateRecovered = stringToDate(dateAsString)
dateRecovered.compare(date) == NSComparisonResult.OrderedSame
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment