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

前端 未结 4 1144
無奈伤痛
無奈伤痛 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 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.

提交回复
热议问题