Question: How do you create a date object from a date in swift xcode.

eg in javascript you would do:
 `var day = new Date('2014-05-20');`

Answer: 
This is best done using an extension to the existing `NSDate` class.

The following extension adds a new initializer which will create a date in the current locale using the date string in the format you specified.

```
extension NSDate
{
    convenience
      init(dateString:String) {
      let dateStringFormatter = NSDateFormatter()
      dateStringFormatter.dateFormat = "yyyy-MM-dd"
      dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
      let d = dateStringFormatter.dateFromString(dateString)!
      self.init(timeInterval:0, sinceDate:d)
    }
 }

```

Now you can create an NSDate from Swift just by doing:

```
NSDate(dateString:"2014-06-06")

```

Please note that this implementation does not cache the NSDateFormatter, which you might want to do for performance reasons if you expect to be creating many `NSDate`s in this way.

Please also note that this implementation will simply crash if you try to initialize an `NSDate` by passing in a string that cannot be parsed correctly. This is because of the forced unwrap of the optional value returned by `dateFromString`. If you wanted to return a `nil` on bad parses, you would ideally use a failible initializer; but you cannot do that now (June 2015), because of a limitation in Swift 1.2, so then you're next best choice is to use a class factory method.

A more elaborate example, which addresses both issues, is here: <https://gist.github.com/algal/09b08515460b7bd229fa> .

---

Update for Swift 5
------------------

```swift
extension Date {
    init(_ dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        let date = dateStringFormatter.date(from: dateString)!
        self.init(timeInterval:0, since:date)
    }
}

```
Personally I think it should be a failable initialiser:

```
extension Date {

    init?(dateString: String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        if let d = dateStringFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since: d)
        } else {
            return nil
        }
    }
}

```

Otherwise a string with an invalid format will raise an exception.