将NSDates天数设置为相同的值

时间:2016-08-03 15:17:24

标签: ios objective-c nsdate

我想比较2个特定日期,但是,我想比较月份和年份,而不是天。例如,我有一个类似2016-08-16的日期,以及2016-08-10之类的其他日期,我需要比较日期并获得平等,因为他们的月份相等。

因此,我需要一种方法来使两个NSDates平等,所以我需要让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");
    }

为了使它工作,我需要“零”NSDates的日期和时间。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

请参阅此答案: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
}

答案 1 :(得分:1)

如果您有两个日期,

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");
}