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

痞子三分冷 提交于 2019-12-19 10:18:05

问题


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...


回答1:


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.




回答2:


You cannot use < or > for comparing dates. You have to use the correct methods. Have a look at this post.




回答3:


    if ([date compare:firstBirthdayDate] == NSOrderedAscending){
         NSLog(@"First date is earlier than today");
    }
   else{
        NSLog(@"First date is later than today");
   }
   if ([date compare:secondBirthdayDate] == NSOrderedAscending){
         NSLog(@"Second date is earlier than today");
   }

   if ([firstBirthdayDate compare: secondBirthdayDate] == NSOrderedSame) 
        NSLog(@"First date is the same as second date");



回答4:


in short: because basic operators only work on primitive types for any OBJECT < > != == ... does a basic operation on the POINTER value of this variable

in c++ those operators can be overwritten in objC and java and other languages you need to use the isEqual function of NSObject



来源:https://stackoverflow.com/questions/13301980/why-cant-nsdate-be-compared-using-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!