Skip to content

Instantly share code, notes, and snippets.

@evgeniyd
Created November 23, 2014 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evgeniyd/306c8f08a7efd2dbddba to your computer and use it in GitHub Desktop.
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
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