我需要在当前日期上加一年(swift 和 iOS 7 及更高版本)。但我发现的每个解决方案都只支持 iOS 8 及更高版本。请指导我通过适当的解决方案。 谢谢
let components: NSDateComponents = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.Year);
let date: NSDate = NSDate()
let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))
最佳答案
NSDateComponents
的setValue()
方法仅适用于
iOS 8/OS X 10.9 或更高版本:
components.setValue(1, forComponent: NSCalendarUnit.Year)
对于 iOS 7 支持,只需使用
components.year = 1
还要注意
dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0)
可以写成更短的
dateByAddingComponents(components, toDate: date, options: [])
关于ios - NSDateComponents.setValue() 不适用于 iOS 7 及更低版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36278943/