user1051935 user1051935 - 6 months ago 16
Objective-C Question

Objective C , comparing two dates

I am trying to compare two dates but I can t see how it works at all ...

this is the code that I am using :

NSCalendar* myCalendar = [NSCalendar currentCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit

fromDate:[NSDate date]];
[components setYear:2012];
[components setMonth:03];
[components setDay:25];
NSDate *startDate = [myCalendar dateFromComponents:components];


NSDateComponents* components2 = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit

fromDate:[NSDate date]];
[components2 setYear:2012];
[components2 setMonth:04];
[components2 setDay:25];
NSDate *endDate = [myCalendar dateFromComponents:components];

NSComparisonResult result1 = [now compare:startDate];
NSComparisonResult result2 = [now compare:endDate];

if (result2 &&

result1
) {
int x =1;
}


the thing is even if the two dates are in the future , i still can get into the if condition ... any reason ?

Answer

The values of result1 and result2 are one of the following.

enum {
    NSOrderedAscending = -1,
    NSOrderedSame,
    NSOrderedDescending
};
typedef NSInteger NSComparisonResult;

The only time (result2 && result1) wouldn't return true is when one of them evaluates to false or 0. This only happens if one of the dates is exactly the same as now.

if (result1 == NSOrderedAscending) {
    // result1 is in the future
}

if (result1 == NSOrderedDescending) {
    // result1 is in the past
}
Comments