Converting NSString to NSDate (and back again)

后端 未结 17 2830
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:26

How would I convert an NSString like \"01/02/10\" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDat

17条回答
  •  生来不讨喜
    2020-11-22 00:01

    You can use extensions for this.

    extension NSDate {
        //NSString to NSDate
        convenience
        init(dateString:String) {
            let nsDateFormatter = NSDateFormatter()
            nsDateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
            // Add the locale if required here
            let dateObj = nsDateFormatter.dateFromString(dateString)
            self.init(timeInterval:0, sinceDate:dateObj!)
        }
    
        //NSDate to time string
        func getTime() -> String {
            let timeFormatter = NSDateFormatter()
            timeFormatter.dateFormat = "hh:mm"
            //Can also set the default styles for date or time using .timeStyle or .dateStyle
            return timeFormatter.stringFromDate(self)
        }
    
        //NSDate to date string
        func getDate() -> String {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd, MMM"
            return dateFormatter.stringFromDate(self)
        }
    
        //NSDate to String
        func getString() -> String {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
            return dateFormatter.stringFromDate(self)
        }
    }
    

    So while execution actual code will look like follows

        var dateObjFromString = NSDate(dateString: cutDateTime)
        var dateString = dateObjFromString.getDate()
        var timeString = dateObjFromString.getTime()
        var stringFromDate = dateObjFromString.getString()
    

    There are some defaults methods as well but I guess it might not work for the format you have given from documentation

        -dateFromString(_:)
        -stringFromDate(_:)
        -localizedStringFromDate(_ date: NSDate,
                         dateStyle dateStyle: NSDateFormatterStyle,
                         timeStyle timeStyle: NSDateFormatterStyle) -> String
    

提交回复
热议问题