一般說到比較大小,我們都會想到比較兩個數字的大小,但是如果讓你比較兩個日期的大小呢,如:比較2016-07-21和2016-08-20的大小,NSDate之間的比較有compare來實現,整理方法,代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date1 = [dateFormatter dateFromString:@"2016-07-21"];
NSDate *date2 = [dateFormatter dateFromString:@"2016-08-20"];
if ([[NSString stringWithFormat:@"%d",[self compareOneDay:date1 withAnotherDay:date2]] isEqualToString:@"1"]) {
NSLog(@"date1 > date2");
}else if ([[NSString stringWithFormat:@"%d",[self compareOneDay:date1 withAnotherDay:date2]] isEqualToString:@"-1"]){
NSLog(@"date1 < date2");
}else{
NSLog(@"date1 = date2");
}
}
#pragma mark - 時間比較大小
- (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
NSLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
if (result == NSOrderedDescending) {
//oneDay > anotherDay
return 1;
}
else if (result == NSOrderedAscending){
//oneDay < anotherDay
return -1;
}
//oneDay = anotherDay
return 0;
}
打印:
2016-08-20 09:41:04.061 CompareDateTime[16742:676557] date1 : 2016-07-20 16:00:00 +0000, date2 : 2016-08-19 16:00:00 +0000
2016-08-20 09:41:04.062 CompareDateTime[16742:676557] date1 < date2