Search code examples
iosobjective-cnsdate

how to sort array of dates in ascending order in ios


I have a NSMutableArray that contains dates in string format. Here I need to sort that array in order of ascending order of dates. I used strong text

 NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
 NSArray *descriptors=[NSArray arrayWithObject: descriptor];
 NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];

But it only sort the dates in terms of ascending order of day and month. Year is not considered. Please help me. For example, Array contains

 03/09/2017, 03/06/2016, 01/06/2016,01/04/2016 and 03/01/2017.

After using the above lines of code, Array contains like,

 01/04/2018, 01/06/2016, 03/01/2017, 03/06/2016, 03/09/2016

Solution

  • You need to use sortedArrayUsingComparator like this way to sort date with String array.

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM/dd/yyyy"];
    NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        NSDate *d1 = [df dateFromString: obj1];
        NSDate *d2 = [df dateFromString: obj2];
        return [d1 compare: d2];
    }];
    

    Note : Set formate of date According to your date, it is hard to predicate date formate from your example thats why I have used MM/dd/yyyy, if your date contain formate dd/MM/yyyy then use that.