2015-01-13 17 views
7

我过去使用以下函数在特定时间间隔上使用NSDateComponents添加到现有日期。如何将一些星期添加到NSDate?

(NSDate *)dateByAddingComponents:(NSDateComponents *)comps 
          toDate:(NSDate *)date 
         options:(NSCalendarOptions)opts 

从iOS8上的周值已弃用的NSDateComponents,这意味着我无法实现我想要做的:通过加入一定的周数给定NSDate生成新NSDate

任何帮助将不胜感激。

+2

一周是7天。 –

+0

你尝试过'weekOfYear'吗? – zaph

回答

6

更新:正如Zaph在回答中所说,Apple实际上建议使用weekOfYearweekOfMonth而不是我提供的答案。查看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]; 
+0

谢谢。你是对的我正在反思它。 – Rich

+0

没问题。它发生了:) –

+0

对不起,但这个答案有可能是错误的,因为它假定每周有7天。 @Zaph的回答更安全。 – rmaddy

-1

您可以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]; 
} 
+0

苹果删除'week'有一个原因,当所有需要的都是使用'weekOfYear'作为文档建议时,不要以另一种形式将它添加回'NSDate'。 – zaph

16

只需使用weekOfYear

苹果文档为NSDateComponentsweek

弃用声明
使用WEEKOFYEAR或weekOfMonth代替,这取决于你想要什么。

NSDate *date = [NSDate date]; 
NSDateComponents *comp = [NSDateComponents new]; 
comp.weekOfYear = 3; 
NSDate *date1 = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0]; 
NSLog(@"date: %@", date); 
NSLog(@"date1: %@", date1); 

输出:

  
date: 2015-01-13 04:06:26 +0000 
date1: 2015-02-03 04:06:26 +0000 

如果使用week你得到这样的警告:

'周' 已过时:在...第一弃用 - 使用weekOfMonth或WEEKOFYEAR ,取决于你的意思

当使用weekOfMonthweekOfYear作为增量时,它们的工作原理相同。他们不同的地方是他们用于获取星期数,你可以得到一个星期的范围是6或者一年中的一周,范围是53.

0

我更喜欢使用dateByAddingUnit。这更直观

return [NSDate[[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitMonth value:3 toDate:toDate options:0];