2011-03-16 71 views
5

我如何只比较2 NSDates的年 - 月 - 日组件?比较NSDate的某些组件?

+0

可能重复[对比的NSDate只有在年月日而言对象(http://stackoverflow.com/questions/3432700/compare-nsdate-objects-only-in - 年份 - 月 - 日) – 2013-08-30 14:53:12

回答

11

因此,这里是你会怎么做:

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 
} 

基本上,我们采取了两个日期,剁下自己的时间 - 分 - 秒位,把它们放回日期。然后,我们比较这些日期(不再有时间分量;只有日期分量),并看看他们如何比较彼此。

警告:在浏览器中键入并且未编译。警告实施者

4

退房这个话题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]; 
    
+0

'NSCalendar'在iOS上工作 – 2011-03-16 21:03:37

+0

太棒了,我曾经在某处读过,可能不会,但是感谢您的验证。 – 2011-03-16 21:04:52

0

从iOS 8开始,您可以使用-compareDate:toDate:toUnitGranularity:方法NSCalendar

像这样:

NSComparisonResult comparison = [[NSCalendar currentCalendar] compareDate:date1 toDate:date2 toUnitGranularity:NSCalendarUnitDay];