@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 @")
}
正如你所看到的,我在第 7 行中清楚地将日期选择器的字符串值转换为 NSDate,但它仍然不允许我使用 dateByAddingTimeInterval
方法,因为它仍然认为它是一个字符串.
最佳答案
看来您所做的与您认为的相反。 dateFormatter.stringFromDate(datePicker.date)
将 NSDate
转换为 String
。如果这是您的意图,您应该在将日期转换为 String
之前将时间间隔添加到日期中。就像这样。
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 @")
关于ios - 将 String 转换为 NSDate 但仍然无法访问 dateByAddingTimeInterval 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38284668/