Last active
August 29, 2015 14:24
-
-
Save drosenstark/89b0337e9f91314458f6 to your computer and use it in GitHub Desktop.
NSDate to String, String to Date in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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