ios 比较两个日期大小

应用中有时候需要选择日期,从而得到一个时间段的记录,但是,我们需要考虑得到的时间段不能超过当前日期

#pragma mark -得到当前时间


NSDateFormatter *formatter=[[NSDateFormatter alloc]init];

[formatter setDateFormat:@"dd-MM-yyyy-HH"];

NSString *dateTime=[formatter stringFromDate:[NSDate date]];

NSDate *currentDate = [formatter dateFromString:dateTime];

NSLog(@"---------- currentDate == %@",date);



#pragma mark -你需要比较的时间

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];

NSDate *date = [dateFormatter dateFromString:@"2016-12-08"];



NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];

NSString *oneDayStr = [dateFormatter stringFromDate:currentDate];

NSString *anotherDayStr = [dateFormatter stringFromDate:date];

NSDate *dateA = [dateFormatter dateFromString:oneDayStr];

NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];

NSComparisonResult result = [dateA compare:dateB];

NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);

if (result == NSOrderedDescending) {

//NSLog(@"Date1  is in the future");

}else if (result == NSOrderedAscending){

//NSLog(@"Date1 is in the past");

}else {

//NSLog(@"Both dates are the same");

}

你可能感兴趣的:(ios 比较两个日期大小)