Created
November 23, 2014 00:32
-
-
Save evgeniyd/306c8f08a7efd2dbddba to your computer and use it in GitHub Desktop.
The basic principle of converting String => NSDate. The gist has both, convenient initializer and class method to create an instance of NSDate
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
import Foundation | |
private var sDateFormatter: NSDateFormatter = NSDateFormatter() | |
extension NSDate | |
{ | |
convenience | |
init?(fromDateString dateString: String) { | |
sDateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" | |
sDateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) | |
sDateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") | |
if let date: NSDate = sDateFormatter.dateFromString(dateString) { | |
self.init(timeInterval: 0.0, sinceDate: date) | |
} else { | |
// Note: The line blow is needed because of "All stored properties of a class | |
// instance must be initialized before returning nil from an initializer" compile error. | |
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases, | |
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed | |
// in future releases, not a feature. | |
self.init() | |
return nil | |
} | |
} | |
class func dateFromString(dateString: String) -> NSDate? { | |
return NSDate(fromDateString: dateString) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment