IOS sorts dates

Source: Internet
Author: User

IOS sorts dates

 

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]);    }

Data needs to be sorted in the project. Here we simulate an array. because the value of the json key returned in the project is null, We need to judge whether obj1 and obj2 are empty during sorting, there are also reasons for ascending and descending order

 

 

Return result = NSOrderedAscending; ascending

 

 

Return result = NSOrderedDescending; in descending order

Ascending result:

 

 

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/072015-06-16 17:16:14.931 TestH5[15888:669365] 2013/03/022015-06-16 17:16:14.931 TestH5[15888:669365] 
 
Descending result:

 

 

2015-06-16 17:17:21.692 TestH5[15946:671080] 2013/03/022015-06-16 17:17:21.692 TestH5[15946:671080] 2013/03/072015-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] 
 



 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.