Ios 如何向NSDate添加周数?
我过去曾使用下面的函数,使用Ios 如何向NSDate添加周数?,ios,objective-c,ios8,nsdate,nsdatecomponents,Ios,Objective C,Ios8,Nsdate,Nsdatecomponents,我过去曾使用下面的函数,使用NSDateComponents向现有日期添加特定的时间间隔 (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts 从iOS8开始,周值不推荐用于NSDateComponents,这意味着我无法实
NSDateComponents
向现有日期添加特定的时间间隔
(NSDate *)dateByAddingComponents:(NSDateComponents *)comps
toDate:(NSDate *)date
options:(NSCalendarOptions)opts
从iOS8开始,周值不推荐用于NSDateComponents
,这意味着我无法实现我想要做的事情:通过向给定的NSDate
添加一定数量的周来生成新的NSDate
任何帮助都将不胜感激 更新:正如扎夫在回答中所说,苹果实际上建议使用
weekOfYear
或weekOfMonth
而不是我提供的答案。查看Zaph的答案了解详细信息
您可能很快就会意识到您想得太多了,但下面介绍了如何在一个日期中添加一定数量的周数,即使周值已被弃用,例如:
NSDateComponents *comp = [NSDateComponents new];
int numberOfDaysInAWeek = 7;
int weeks = 3; // <-- this example adds 3 weeks
comp.day = weeks * numberOfDaysInAWeek;
NSDate *date = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];
NSDateComponents*comp=[NSDateComponents new];
int numberOfDaysInAWeek=7;
整数周=3;// 您可以使用以下方法在NSDate添加类别:
- (NSDate *) addWeeks:(NSInteger)weeks
{
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.day = weeks * 7;
return [gregorian dateByAddingComponents:components toDate:self options:0];
}
只需使用weekOfYear
:
苹果公司关于NSDATE组件的文档
周
:
弃用声明根据您的意愿,改用weekOfYear或weekOfMonth 输出: date: 2015-01-13 04:06:26 +0000 date1: 2015-02-03 04:06:26 +0000 日期:2015-01-13 04:06:26+0000 日期1:2015-02-03 04:06:26+0000 如果您使用
week
,您将收到以下警告:
“周”已弃用:首次弃用于…-使用weekOfMonth或weekOfYear,具体取决于您的意思
当使用
weekOfMonth
或weekOfYear
作为增量时,它们的工作原理相同。它们的不同之处在于,当它们用于获取周数时,您将获取范围为6的当月周或范围为53的全年周。我更喜欢使用dateByAddingUnit。这更直观
return [NSDate[[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitMonth value:3 toDate:toDate options:0];
你试过一周了吗?没问题。发生了:)对不起,但这个答案有可能是错误的,因为它假设每个星期正好有7天。@Zaph的答案更安全。@rmaddy无需道歉。我不知道有哪种情况下,几周没有整整7天(可能是夏令时?),我也不知道有一个一周或一周的财产;但如果苹果公司说用weekOfYear或weekOfMonth来代替,那就是应该使用的。我将对此进行更多的研究,找出weekOfYear和weekOfMonth之间的差异,然后进行相应的更新。谢谢@LyndseyScott承认,我不知道在什么情况下使用“天*7”会产生与使用“周年”不同的结果,但会想到日光节约和闰年(或闰秒)。当使用
weekOfMonth
或weekOfYear
来增加或减少日期时,它们的作用是相同的。它们的不同之处在于用于获取周数的时间苹果删除了week
,当需要使用weekOfYear
时,不要以另一种形式将其添加回NSDate
,这是有原因的。
return [NSDate[[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitMonth value:3 toDate:toDate options:0];