2011-03-16 70 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];