Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't NSDate be compared using < or >?

NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSLog([@"today is " stringByAppendingString:[dateFormat stringFromDate:date]]);
NSLog([@"firstBirthdayDate is " stringByAppendingString:[dateFormat stringFromDate:firstBirthdayDate]]);
NSLog([@"secondBirthdayDate is " stringByAppendingString:[dateFormat stringFromDate:secondBirthdayDate]]);
if ([firstBirthdayDate isEqualToDate:secondBirthdayDate])
    NSLog(@"First date is the same as second date");
if (firstBirthdayDate < date)
    NSLog(@"First date is earlier than today");
else
    NSLog(@"First date is later than today");

if (secondBirthdayDate < date)
    NSLog(@"Second date is earlier than today");
  • Today is 11/08/2012
  • firstBirthdayDate is 01/23/2012
  • secondBirthdayDate is 01/23/2012

Here's what I get in the log:

First date is the same as second date

First date is later than today

Second date is earlier than today

I think I'm going crazy...

like image 488
taralex Avatar asked Jul 04 '26 10:07

taralex


1 Answers

Use if ([date1 isEqualToDate:date2]) for comparing two dates or else you can use the following,

if ([date1 compare:date2] == NSOrderedSame)

if ([date1 compare:date2] == NSOrderedAscending)

if ([date1 compare:date2] == NSOrderedDescending)

>, < or = are only for comparing non-pointers. Basically my understanding is that when you are using these operators, it might be comparing the memory addresses rather than the values in it. So you will get unexpected results.

Logically, this is how it works:

    if (obj1 > obj2) {
        return NSOrderedDescending;
    }

    if (obj1 < obj2) {
        return NSOrderedAscending;
    }

    if (obj1 == obj2) {
        return NSOrderedSame;
    }

You can use any of the compare statements to compare dates.

like image 113
iDev Avatar answered Jul 07 '26 04:07

iDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!