我一直在使用dateByAddingComponents:toDate:options:
和dateByAddingUnit:value:toDate:options:
,并使用可选的结合来获得日期出来。就像这样:什么时候做dateByAddingComponents:toDate:options return nil?
guard let startOfNextMonth = calendar.dateByAddingComponents(oneMonthComponent, toDate: startOfThisMonth, options: []) else {
return nil
}
哪里oneMonthComponent
只是一个NSDateComponent设置为1
当我读到它月份值,在文档中他们都这样说:
返回如果日期超出接收器定义的范围或计算无法执行,则为零。
而且我一直在想,当恰好造成的。如果我只是在某个日期添加一个月,有没有可能是零的方法?这是否是因为其他日历系统中的某些差异,其中添加了一些单位没有意义?
找遍四周,已经无法找到这样的情况:它会返回零。
有什么事情可以让上面的代码是零?什么是添加组件的例子可能是零?
请注意,在Swift> = 3中,方法名是'date(byAdding:to:options:)'。 –