Created
September 29, 2015 15:07
-
-
Save eric-robinson/f07943b1806cca51e54a to your computer and use it in GitHub Desktop.
Add NSDate support to NSUserDefaults
This file contains 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
import Foundation | |
// ISO Formatting | |
extension NSDate { | |
static func ISOStringFromDate(date: NSDate) -> String { | |
let dateFormatter = NSDateFormatter() | |
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") | |
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT") | |
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" | |
return dateFormatter.stringFromDate(date).stringByAppendingString("Z") | |
} | |
static func dateFromISOString(string: String) -> NSDate? { | |
let dateFormatter = NSDateFormatter() | |
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") | |
dateFormatter.timeZone = NSTimeZone.localTimeZone() | |
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" | |
return dateFormatter.dateFromString(string) | |
} | |
} | |
// NSUserDefaults + NSDate | |
extension NSUserDefaults { | |
func dateForKey(defaultName: String) -> NSDate? { | |
if let stringForKey = self.stringForKey(defaultName) { | |
return NSDate.dateFromISOString(stringForKey) | |
} | |
return nil | |
} | |
func setDate(date: NSDate, forKey defaultName:String) { | |
self.setValue(NSDate.ISOStringFromDate(date), forKey: defaultName) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment