How can I convert string date to NSDate?

前端 未结 18 1907
花落未央
花落未央 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:52

    The code fragments on this QA page are "upside down"...

    The first thing Apple mentions is that you cache your formatter...

    Link to Apple doco stating exactly how to do this:

    Cache Formatters for Efficiency Creating a date formatter is not a cheap operation. ...cache a single instance...

    Use a global...

    let df : DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter 
    }()
    

    Then simply use that formatter anywhere...

    let s = df.string(from: someDate)
    

    or

    let d = df.date(from: someString)
    

    Or use any of the other many, many convenient methods on DateFormatter.

    It is that simple.

    (If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)

    Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.

提交回复
热议问题