swift - 使用 NSDate() 快速创建 future 日期

标签 swift nscalendar

我收到一个错误:“调用中缺少参数‘coder’的参数”以下代码:

var components = NSDateComponents()     
components.setValue(1,forComponent: NSCalendarUnit.CalendarUnitMonth);
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components,       toDate: NSDate(),options:0)

文档要求:

NSCalendar.currentCalendar().dateByAddingComponents(<#comps: NSDateComponents?#>, toDate: <#NSDate?#>, options: <#NSCalendarOptions#>)

任何人都可以看到我错过了什么吗?我没有看到名为“coder”的参数是必需的。

最佳答案

看起来怎么样

swift 4.x

let date = Date()
var components = DateComponents()
components.setValue(1, for: .month)
let expirationDate = Calendar.current.date(byAdding: components, to: date)

swift 2.0

let components: NSDateComponents = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.Month);
let date: NSDate = NSDate()
let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))

swift 1.2

var components = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitMonth);
let date: NSDate = NSDate()
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(0))

目标-C

NSDate *date = [NSDate new];  
NSDateComponents *components = [NSDateComponents new];
components.month = 1;
NSDate *expirationDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:0];

关于swift - 使用 NSDate() 快速创建 future 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24741038/

相关文章:

swift - 按名称获取导出变量

ios - UITableViewRowAction - 保留单元格的文本

java - 如何操作我从我的应用程序启动的应用程序

cocoa-touch - NSCalendar dateFromComponents 返回错误的日期

cocoa - 从 NSDate 中剥离时间

ios - 如何获取带有导航栏的特定 uitableviewcell 屏幕截图?

objective-c - 我们如何将一个可选的枚举值从 Swift 返回到 Obj-C?

ios - 如何减去日期成分?

ios - iOS 应用是否必须适用于所有日历

iphone - NSDate、NSCalendar 和 NSDateComponents 计时