您可以使用 NSDateComponents 类来直接访问 NSDate 实例的日、月和年。
NSDate *someDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:someDate];
NSLog(@"Year: %d", [components year]);
NSLog(@"Month: %d", [components month]);
NSLog(@"Day: %d", [components day]);
这是一个 NSDateComponents 比较方法:
- (BOOL)isFirstCalendarDate:(NSDateComponents *)first beforeSecondCalendarDate:(NSDateComponents *)second
{
if ([first year] < [second year]) {
return YES;
} else if ([first year] == [second year]) {
if ([first month] < [second month]) {
return YES;
} else if ([first month] == [second month]) {
if ([first day] < [second day]) {
return YES;
}
}
}
return NO;
}
我没有测试过 NSDateComponents 比较方法;它将受益于单元测试。