Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an NSArray of strings in date format @"Aug 2013" in ascending order..?

I have an array of NSString objects in the format... @"Aug 2013" @"July 2013" and so on...

I want to sort this array in ascending order.. Is getting the date first for individual value a good idea..?

like image 512
Ankit Srivastava Avatar asked Dec 07 '22 05:12

Ankit Srivastava


1 Answers

An other solution in one block

NSArray* array = [NSArray arrayWithObjects:@"Janvier 2012",@"Mars 2013", @"Juin 2013", @"Octobre 2012", nil];

NSArray* result = [array sortedArrayUsingComparator:^(id a, id b) {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM YYYY"];

    NSDate* datea = [dateFormat dateFromString:a];
    NSDate* dateb = [dateFormat dateFromString:b];

    return [datea compare:dateb];
}];
like image 67
tdelepine Avatar answered Mar 15 '23 01:03

tdelepine