gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:15:26 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com