比较NSDate的某些组件?

Doo*_*oom 5 iphone comparison nsdate

我如何只比较2的年 - 月 - 日组件NSDates

Dav*_*ong 11

所以这就是你如何做到的:

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
}
Run Code Online (Sandbox Code Playgroud)

基本上,我们采取两个日期,砍掉他们的小时 - 分钟 - 秒位,然后将它们变回日期.然后我们比较那些日期(不再有时间组件;只有日期组件),看看他们如何比较彼此.

警告:键入浏览器但未编译.警告实施者