一般说到比较大小,我们都会想到比较两个数字的大小,但是如果让你比较两个日期的大小呢,如:比较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