will cohen will cohen - 4 months ago 14
Swift Question

Convert String to NSDate but still not accessing dateByAddingTimeInterval method

@IBAction func onDateChanged(sender: AnyObject) {
let dateFormatter = NSDateFormatter()

// dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

let strDate = dateFormatter.stringFromDate(datePicker.date)

let timeinterval = NSTimeInterval.abs(17 * 60) //time in seconds
let newDate = strDate.dateByAddingTimeInterval(-timeinterval)
// ERROR =- on the above line I get an error saying that type String does not have a method called dateByAddingTimeInterval, however I made the string a NSDate value in the variable newDate.


print("\(strDate) is the date on the datePicker @")
}


Hello, as you can see I clearly converted the string value of the date picker into an NSDate in line 7, but it still is not letting me use the dateByAddingTimeInterval method because it still thinks it is a string. Any help or suggestions are greatly appreciated. Thanks in advanced!

Answer

It looks like you did the opposite of what you thought you were doing. dateFormatter.stringFromDate(datePicker.date) converts a NSDate to a String. If this was your intention, you should add your time interval to the date before converting it to a String. Like so.

let timeinterval = NSTimeInterval.abs(17 * 60) //time in seconds
let newDate = datePicker.date.dateByAddingTimeInterval(-timeinterval)
let strDate = dateFormatter.stringFromDate(newDate)
print("\(strDate) is the date on the datePicker @")