drbj drbj - 5 months ago 28
Objective-C Question

NSDate compare always returns NSOrderedAscending

I am checking if a given date & time is already past the current date & time. Here's what I've done

NSString *End = [[values objectAtIndex:index]valueForKey:@"EndTime"];

fmt.dateFormat = @"yyyy-MM-dd hh:mm:ss";
utc = [fmt dateFromString:End];
NSDate *endDateInLocalTimezone = [utc dateByAddingTimeInterval:timeZoneSeconds];
fmt.dateFormat = @"MMMM dd, hh:mm a";
endDateInLocalTimezone = [fmt stringFromDate:endDateInLocalTimezone];

NSDate *now = [NSDate date];
now = [fmt stringFromDate:now];

if([endDateInLocalTimezone compare:now] == NSOrderedAscending)

I got a July 03, 5:29 PM endDateInLocalTimezone and comparing it to my now which is June 30, 12:18 PM. It still say's that is in NSOrderedAscending, which means the left operand is smaller than the right operand. But in the given case, the right operand is smaller than the left operand. Why is it still getting inside the if?

Rob Rob

You are comparing string renditions of the date objects, rather than the date objects, themselves. Compare dates, not strings.

For example:

NSString *dateString = values[index][@"EndTime"];

formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];           // the EndTime is in GMT/UTC, tell you formatter that
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; // you generally should make sure to use `en_US_POSIX` in case user is not using gregorian calendar
NSDate *date = [fmt dateFromString:dateString];

NSDate *now = [NSDate date];

if ([date compare:now] == NSOrderedAscending) {