Deepak Thakur Deepak Thakur - 3 months ago 16
Objective-C Question

Check if NSDate is in next week

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

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

- (NSInteger)thisW:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];

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);
if(todaysWeek==datesWeek){
//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

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