如果我有一个像 04-30-2006 这样的日期 我怎样才能拆分并得到月、日和年
还有什么直接比较年份的方法吗?
最佳答案
你必须使用 NSDateComponents。像这样:
NSDate *date = [NSDate date];
NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:componentFlags fromDate:date];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
Alsois there any direct way of comparing the years ?
不是内置的。但是你可以为它写一个类别。像这样:
@interface NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate;
@end
@implementation NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate {
NSDateComponents *myComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self];
NSDateComponents *otherComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:compareDate];
if ([myComponents year] == [otherComponents year]) {
return YES;
}
return NO;
}
@end
关于iphone - 将 NSDate 拆分为年月日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4976822/