ios - 将 String 转换为 NSDate 但仍然无法访问 dateByAddingTimeInterval 方法

标签 ios swift string nsdate

   @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/

相关文章:

ios - Swift:将照片图像加载到应用程序中

ios - 自定义 UIView 子类中的中心 CAShapeLayer

ios - ld : library not found for -lyoutube-ios-player-helper

c# - 如何在控制台应用程序中使文本为 "typed out"?

java - 按空格分割字符串

android - 在 MySQL 中存储 PhoneGap 的 device.uuid 的最佳字段类型

ios - UISplitView:当分割 View 弹出窗口出现时关闭另一个弹出窗口

c++ - Memcpy、字符串和终止符

ios - 在 GLKit (iOS 5) 中使用 GL_POINTS

ios - UIAlertController + UIProgressView + macCatalyst