【发布时间】:2011-03-16 20:45:40
【问题描述】:
如何仅比较 2 NSDates 的年月日分量?
【问题讨论】:
标签: iphone comparison nsdate
如何仅比较 2 NSDates 的年月日分量?
【问题讨论】:
标签: iphone comparison 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 get year/month/day
取出日/月/年后,您可以将它们作为整数进行比较。
如果你不喜欢这种方法
相反,你可以试试这个..
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];
还有一种方式……
NSDateComponents *dateComp = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComp year];
NSInteger month = [dateComp month];
NSInteger day = [dateComp day];
【讨论】:
从 iOS 8 开始可以使用NSCalendar 的-compareDate:toDate:toUnitGranularity: 方法。
像这样:
NSComparisonResult comparison = [[NSCalendar currentCalendar] compareDate:date1 toDate:date2 toUnitGranularity:NSCalendarUnitDay];
【讨论】:
使用-[NSDate compare:] 方法 - NSDate Compare Reference
【讨论】: