How to add a number of weeks to an NSDate?

自闭症网瘾萝莉.ら 提交于 2019-12-01 17:40:38

Update: As Zaph said in his answer, Apple actually recommends using weekOfYear or weekOfMonth instead of the answer I provided. View Zaph's answer for details.


You'll probably quickly realize that you're overthinking it, but here's how you can add a certain number of weeks to a date even though the week value's been deprecated, ex:

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];

Just use weekOfYear:

Apple docs for NSDateComponents week:

Deprecation Statement
Use weekOfYear or weekOfMonth instead, depending on what you intend.

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);

Output:

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

If you use week you get this warning:

'week' is deprecated: first deprecated in ... - Use weekOfMonth or weekOfYear, depending on which you mean

When using the weekOfMonth or weekOfYear as a delta they work the same. Where they are different is when they are used to obtain the week number where you will get the week of the month with a range of 6 or the week of the year with a range of 53.

I prefer to use dateByAddingUnit. It's more intuitive

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

You can add a category on NSDate with the following method:

- (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];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!