Comparison of some NSDate components?

How can I compare only the components of year-month-day 2 NSDates?

+5
source share
4 answers

So how do you do this:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDate *firstDate = ...; // one date
NSDate *secondDate = ...; // the other date

NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:firstDate];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate:secondDate];

NSDate *truncatedFirst = [calendar dateFromComponents:firstComponents];
NSDate *truncatedSecond = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [truncatedFirst compare:truncatedSecond];
if (result == NSOrderedAscending) {
  //firstDate is before secondDate
} else if (result == NSOrderedDescending) {
  //firstDate is after secondDate
}  else {
  //firstDate is the same day/month/year as secondDate
}

Basically, we take two dates, beat their hours-minutes-seconds and turn them back to dates. Then we compare these dates (which no longer have a time component, just a date component) and see how they compare with eachother.

WARNING: typed in a browser and not compiled. Warning

+11
source

See this topic NSDate get year / month / day

Once you select day / month / year, you can compare them as integers.

.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy"];
int year = [[dateFormatter stringFromDate:[NSDate date]] intValue];

[dateFormatter setDateFormat:@"MM"];
int month = [[dateFormatter stringFromDate:[NSDate date]] intValue];

[dateFormatter setDateFormat:@"dd"];
int day = [[dateFormatter stringFromDate:[NSDate date]] intValue];
  • ...

    NSDateComponents *dateComp = [calendar components:unitFlags fromDate:date];
    
    NSInteger year = [dateComp year];
    
    NSInteger month = [dateComp month];
    
    NSInteger day = [dateComp day];
    
+4

With iOS 8, you can use the -compareDate:toDate:toUnitGranularity:method NSCalendar.

Like this:

    NSComparisonResult comparison = [[NSCalendar currentCalendar] compareDate:date1 toDate:date2 toUnitGranularity:NSCalendarUnitDay];
0
source

Using a Method -[NSDate compare:]- NSDate Comparison Help

-1
source

All Articles