1

如果我打电话

NSDateComponents * components = [calendar components:(NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:self];

而不是问,让我们说

components.minute

它会保证给我 0 吗?

我做了 像这样,但是为了确保它 100% 正常工作,上述条件也需要针对 iOS 的下一个版本进行处理

- (BOOL)isInTheSameComponents:(NSUInteger)components withDate:(NSDate *)date {

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components1 = [calendar components:components fromDate:self];
    NSDateComponents *components2 = [calendar components:components fromDate:date];

    return ((components1.month == components2.month) && (components1.year == components2.year) && (components1.day == components2.day) && (components1.hour == components2.hour) && (components1.minute == components2.minute));

}

- (BOOL)isInTheSameMonthAndYearWithDate:(NSDate *)date {

    return [self isInTheSameComponents:(NSMonthCalendarUnit | NSYearCalendarUnit) withDate:date];
}
4

1 回答 1

1

为了避免这种(可能是未定义的)行为,只需测试您正在提取的组件:

- (BOOL)isInTheSameComponents:(NSUInteger)components withDate:(NSDate *)date {

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components1 = [calendar components:components fromDate:self];
    NSDateComponents *components2 = [calendar components:components fromDate:date];

    if ((components & NSYearCalendarUnit) != 0 && components1.year != components2.year)
        return NO;
    if ((components & NSMonthCalendarUnit) != 0 && components1.month != components2.month)
        return NO;
    if ((components & NSDayCalendarUnit) != 0 && components1.day != components2.day)
        return NO;
    if ((components & NSHourCalendarUnit) != 0 && components1.hour != components2.hour)
        return NO;
    if ((components & NSMinuteCalendarUnit) != 0 && components1.minute != components2.minute)
        return NO;
    // and any other components you might use
    return YES;
}

我建议为这种方法取一个更好的名称:

- (BOOL)isEqualToComponents:(NSUInteger)components inDate:(NSDate *)date
{
   ...
}

(我假设这是一个NSDate类别)

于 2013-06-05T11:55:23.310 回答