How to sort the Array that contains date in string

2019-08-29 12:23发布

问题:

I have array of dictionaries ,In every dictionary contains one date parameter . The array of date parameters(contains in dictionaries) as follow:

 [@"16-1-2015 7:00PM",@"15-1-2014 11:30AM",@"14-1-2014 7:00PM",
 @"15-1-2015 6:30AM ".@"16-1-2015 8:30PM"]

I need output like :

[@"16-1-2015 8:30PM",@"16-1-2015 7:00PM",@"15-1-2015 6:30AM ",
@"15-1-2014 11:30AM",@"14-1-2014 7:00PM"];

回答1:

You could try this:

NSArray *dateStringArray = @[ @"16-1-2015 7:00PM", @"15-1-2014 11:30AM", @"14-1-2014 7:00PM", @"15-1-2015 6:30AM ", @"16-1-2015 8:30PM" ];

 - (NSArray *)sortDateStringArray:(NSArray *)dateStringArray
    {
        NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
        [dateFormater setDateFormat:@"dd-MM-yyyy h:mma"];
        NSArray *sortedArray = [dateStringArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
          NSDate *date1 = [dateFormater dateFromString:obj1];
          NSDate *date2 = [dateFormater dateFromString:obj2];
          return [date2 compare:date1];
        }];
        return sortedArray;
    }

I think it better convert your dateString to NSDate then compare
Hope this help !!!



回答2:

Store the dates as NSDate objects in an NSMutableArray, then use -[NSArray sortedArrayUsingSelector:] or -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter. The -[NSDate compare:] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)

Or

If I have an NSMutableArray of objects with a field "beginDate" of type NSDate I am using an NSSortDescriptor as below:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

please visit this question: here