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"];
Huy Nghia
  • 996
  • 8
  • 22

2 Answers2

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

Huy Nghia
  • 996
  • 8
  • 22
  • 1
    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. – David Berry Feb 25 '15 at 07:27
  • 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]; – Shobhit C Aug 22 '17 at 07:47
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

Community
  • 1
  • 1
Ravi Chhatrala
  • 324
  • 4
  • 14