How can I convert string date to NSDate?

Shardul picture Shardul · Jul 16, 2014 · Viewed 195.5k times · Source

I want to convert "2014-07-15 06:55:14.198000+00:00" this string date to NSDate in Swift.

Answer

x4h1d picture x4h1d · Jul 16, 2014

try this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.

Swift 3 and later (Swift 4 included)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here