如果我打电话
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];
}
答案 0 :(得分: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
类别)