How to sort the Array that contains date in strings in ascending order

霸气de小男生 提交于 2019-12-25 01:56:00

问题


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



来源:https://stackoverflow.com/questions/28711360/how-to-sort-the-array-that-contains-date-in-strings-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!