码迷,mamicode.com
首页 > 移动开发 > 详细

IOS对日期进行排序

时间:2015-06-16 19:20:41      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"2019/03/01/",@"2013/03/02",@"2013/03/07",@"2014/03/01/", [NSNull null], nil];
    
    array = (NSMutableArray *)[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy/MM/dd/"];
        if (obj1 == [NSNull null]) {
            obj1 = @"0000/00/00";
        }
        if (obj2 == [NSNull null]) {
            obj2 = @"0000/00/00";
        }
        NSDate *date1 = [formatter dateFromString:obj1];
        NSDate *date2 = [formatter dateFromString:obj2];
        NSComparisonResult result = [date1 compare:date2];
        return result == NSOrderedAscending;
    }];
    for (int i = 0; i < [array count]; i++) {
        NSLog(@"%@", [array objectAtIndex:i]);
    }

在项目里需要对数据进行排序,这里模拟一个数组,由于项目中返回的json的key对应的value为空,所以排序的时候需要判断obj1和obj2是否为空,还有升序和降序的问题根据

return result == NSOrderedAscending;  升序

return result == NSOrderedDescending; 降序

升序结果:

2015-06-16 17:16:14.930 TestH5[15888:669365] 2019/03/01/
2015-06-16 17:16:14.930 TestH5[15888:669365] 2014/03/01/
2015-06-16 17:16:14.931 TestH5[15888:669365] 2013/03/07
2015-06-16 17:16:14.931 TestH5[15888:669365] 2013/03/02
2015-06-16 17:16:14.931 TestH5[15888:669365] <null>
降序结果:

2015-06-16 17:17:21.692 TestH5[15946:671080] 2013/03/02
2015-06-16 17:17:21.692 TestH5[15946:671080] 2013/03/07
2015-06-16 17:17:21.692 TestH5[15946:671080] 2014/03/01/
2015-06-16 17:17:21.692 TestH5[15946:671080] 2019/03/01/
2015-06-16 17:17:21.692 TestH5[15946:671080] <null>




IOS对日期进行排序

标签:

原文地址:http://blog.csdn.net/jwzhangjie/article/details/46519805

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!