How can I convert string date to NSDate?

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

    Swift support extensions, with extension you can add a new functionality to an existing class, structure, enumeration, or protocol type.

    You can add a new init function to NSDate object by extenging the object using the extension keyword.

    extension NSDate
    {
        convenience
        init(dateString:String) {
            let dateStringFormatter = NSDateFormatter()
            dateStringFormatter.dateFormat = "yyyyMMdd"
            dateStringFormatter.locale = NSLocale(localeIdentifier: "fr_CH_POSIX")
            let d = dateStringFormatter.dateFromString(dateString)!
            self.init(timeInterval:0, sinceDate:d)
        }
    } 
    

    Now you can init a NSDate object using:

    let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")
    

提交回复
热议问题