我如何只比较2 NSDates的年月日部分?

最佳答案

因此,这是您的处理方式:

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
}

基本上,我们采用两个日期,将它们的小时-分钟-秒位去掉,然后将它们重新转换为日期。然后,我们比较这些日期(不再具有时间成分;仅包含日期成分),并观察它们之间的比较。

警告:在浏览器中键入,未编译。注意事项实现者

关于iphone - 比较NSDate的某些组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5331512/

10-12 01:59