Objective-C Language Comparaison de date


Exemple

Il y a 4 méthodes pour comparer NSDate dans Objective-C:

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

Considérez l'exemple suivant en utilisant 2 dates, NSDate date1 = July 7, 2016 et NSDate 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 

Maintenant que les NSDate sont créés, ils peuvent être comparés:

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

Nous pouvons également utiliser les earlierDate: et laterDate: de la classe NSDate :

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.

Enfin, nous pouvons utiliser la NSDate compare: :

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
    }