我可以比較日期:設定Date1 = 2011-10-14
和Date2 =2011-10-20
。但是我想實現的是判斷15號是否在Date1和Date2之間。代碼如下:
if ( [date compare:Date1] == NSOrderedDescending && [date compare:Date2] ==
NSOrderedAscending) { //****** }
但是沒有成功,請高手指點如何實現。謝謝!
試試下面的代碼:其中Date1和Date2是判斷的范圍
NSCalendar *calendar= [NSCalendar currentCalendar];
NSInteger desiredComponents= (NSDayCalendarUnit | NSMonthCalendarUnit);
NSDateComponents *firstComponents= [calendar components:desiredComponents fromDate:Date1];
NSDateComponents *secondComponents= [calendar components:desiredComponents fromDate:Date2];
NSDate *firstWOYear= [calendar dateFromComponents:firstComponents];
NSDate *SecondWOYear = [calendar dateFromComponents:secondComponents];
NSComparisonResult result= [firstWOYear compare:SecondWOYear];
if (result== NSOrderedAscending) {
} else if (result== NSOrderedDescending) {
} else {
}