swiftstringtype-conversionnsdate

How can I convert string date to NSDate?


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


Solution

  • 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

    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
    

    Edit:

    Alternative date time format reference https://unicode-org.github.io/icu/userguide/format_parse/datetime/