How can I convert string date to NSDate?

前端 未结 18 1709
花落未央
花落未央 2020-11-22 16:14

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

18条回答
  •  花落未央
    2020-11-22 16:58

    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
    

提交回复
热议问题