将 NSDates 天设置为相同的值

Set NSDates days to same value

我想比较 2 个特定的日期,但是,我想比较月份和年份,而不是日期。例如,我有一个日期是 2016-08-16,另一个日期是 2016-08-10,我需要比较日期并获得相等性,因为它们的月份相等。

因此,我需要一种方法使两个 NSDate 的日期相同,因此我需要将 2016-08-10 设为 2016-08-00。之后我也可以修改第二个日期并进行比较。

我有简单的平等代码片段,但我想它也考虑了天数和小时数等:

 if ([dateOld compare:dateNew] == NSOrderedDescending) {
        NSLog(@"date1 is later than date2");
    } else if ([dateOld compare:dateNew] == NSOrderedAscending) {
        NSLog(@"date1 is earlier than date2");
    } else {
        NSLog(@"dates are the same");
    }

为了让它工作,我需要 "zero" 天和时间的 NSDates。有什么办法吗?

看到这个 SO 答案:Comparing certain components of NSDate?

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (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 month/year as secondDate
}

如果你有两个约会对象,

NSDate *now = // some date
NSDate *other = // some other date

你可以这样比较:

if ([[NSCalendar currentCalendar] compareDate:now toDate:other toUnitGranularity:NSCalendarUnitMonth] == NSOrderedSame) {
    NSLog(@"Same month");
} else {
    NSLog(@"Different month");
}