0

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"];
2

2 Answers 2

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 !!!

Sign up to request clarification or add additional context in comments.

2 Comments

Note that if you swap the compare operands, you can eliminate the switch statement: return [date2 compare:date1]; Also note that constructing NSDateFormatter is an expensive operation, at a minimum it should be elevated to outside the block.
Thanks man. Saved my day. @HuyNghia : Just a heads up, the above code is for sorting in descending order. To make it ascending sort, just replace date1 with date2 on this line: return [date2 compare:date1];
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.