日期比较

在 Objective-C 中有 4 种比较 NSDates 的方法:

  • - (BOOL)isEqualToDate:(NSDate *)anotherDate
  • - (NSDate *)earlierDate:(NSDate *)anotherDate
  • - (NSDate *)laterDate:(NSDate *)anotherDate
  • - (NSComparisonResult)compare:(NSDate *)anotherDate

考虑使用 2 个日期 NSDate date1 = July 7, 2016NSDate date2 = July 2, 2016 的以下示例:

NSDateComponents *comps1 = [[NSDateComponents alloc]init];
comps.year = 2016;
comps.month = 7;
comps.day = 7;

NSDateComponents *comps2 = [[NSDateComponents alloc]init];
    comps.year = 2016;
    comps.month = 7;
    comps.day = 2;

NSDate* date1 = [calendar dateFromComponents:comps1]; //Initialized as July 7, 2016 
NSDate* date2 = [calendar dateFromComponents:comps2]; //Initialized as July 2, 2016 

现在创建了 NSDates,可以比较它们:

if ([date1 isEqualToDate:date2]) {
    //Here it returns false, as both dates are not equal
}

我们也可以使用 NSDate 类的 earlierDate:laterDate:方法:

NSDate *earlierDate = [date1 earlierDate:date2];//Returns the earlier of 2 dates. Here earlierDate will equal date2.
NSDate *laterDate = [date1 laterDate:date2];//Returns the later of 2 dates. Here laterDate will equal date1.

最后,我们可以使用 NSDatecompare:方法:

NSComparisonResult result = [date1 compare:date2];
    if (result == NSOrderedAscending) {
        //Fails
        //Comes here if date1 is earlier than date2. In our case it will not come here.
    }else if (result == NSOrderedSame){
        //Fails
        //Comes here if date1 is the same as date2. In our case it will not come here.
    }else{//NSOrderedDescending
        
        //Succeeds
        //Comes here if date1 is later than date2. In our case it will come here
    }