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

前端 未结 4 1145
無奈伤痛
無奈伤痛 2021-01-14 09:48
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@\"MM/dd/yyyy\"];
NSLog([@\"today is \" stringBy         


        
相关标签:
4条回答
  • 2021-01-14 09:56
        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");
    
    0 讨论(0)
  • 2021-01-14 10:01

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

    0 讨论(0)
  • 2021-01-14 10:01

    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

    0 讨论(0)
  • 2021-01-14 10:03

    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.

    0 讨论(0)
提交回复
热议问题