Comparing certain components of NSDate?

前端 未结 4 457
青春惊慌失措
青春惊慌失措 2021-01-05 21:35

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

4条回答
  •  星月不相逢
    2021-01-05 22:11

    So here's how you'd do it:

    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 the two dates, chop off their hours-minutes-seconds bits, and the turn them back into dates. We then compare those dates (which no longer have a time component; only a date component) and see how they compare to eachother.

    WARNING: typed in a browser and not compiled. Caveat implementor

提交回复
热议问题