我该如何仅比较两个
NSDate
对象的年月日组件?NSDate
对象的年月日组件?下面是做法:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | 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 day/month/year as secondDate
}
基本上,我们取两个日期,去掉它们的小时-分钟-秒的部分,然后将它们转换回日期。然后我们比较这些日期(不再具有时间组件,只有日期组件),并查看它们如何相互比较。
警告:在浏览器中输入,未经编译。实现者注意。
请查看这个主题 NSDate获取年/月/日
一旦你提取出了日/月/年,你可以将它们作为整数进行比较。
如果你不喜欢那种方法
相反,你可以尝试这个...
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
int year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
[dateFormatter setDateFormat:@"MM"];
int month = [[dateFormatter stringFromDate:[NSDate date]] intValue];
[dateFormatter setDateFormat:@"dd"];
int day = [[dateFormatter stringFromDate:[NSDate date]] intValue];
And another way...
NSDateComponents *dateComp = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComp year];
NSInteger month = [dateComp month];
NSInteger day = [dateComp day];
NSCalendar
的-compareDate:toDate:toUnitGranularity:
方法。 NSComparisonResult comparison = [[NSCalendar currentCalendar] compareDate:date1 toDate:date2 toUnitGranularity:NSCalendarUnitDay];