Deepak Thakur Deepak Thakur - 1 year ago 90
Objective-C Question

Check if NSDate is in next week

I tried the following code, but I do not get a condition where the

is in next week. How will I know that the
which is parameter in the function falls in next week? Following code always returns 1.

- (NSInteger)thisW:(NSDate *)date
NSCalendar *gregorian = [[NSCalendar alloc]

NSDateComponents *todaysComponents =
[gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSUInteger todaysWeek = [todaysComponents weekOfYear];

NSDateComponents *otherComponents =
[gregorian components:NSYearCalendarUnit fromDate:date];

NSUInteger datesWeek = [otherComponents weekOfYear];
//NSLog(@"Date %@",date);
//NSLog(@"Date is in this week");
return 1;
}else if(todaysWeek+1==datesWeek){
//NSLog(@"Date is in next week");
return 2;
} else {
return 0;


Answer Source

You need to pass NSCalendarUnitWeekOfYear when extracting date components:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download