一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

iOS 时间(年月日)大小的比较的例子

时间:2022-06-25 23:34:46 编辑:袖梨 来源:一聚教程网

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

热门栏目