I have an array contains NSDictionary objects, and one key is Time, which contains time string format like "2013-10-09", and I need to sort the array by the Time key, but I don't know how to sort NSString with that format.
Asked
Active
Viewed 193 times
3 Answers
0
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:datesAry.count];
for (NSString *dateString in dates)
{
NSDate *date = [dateFormatter dateFromString:timeString];
[dates addObject:date];
}
[dates sortUsingSelector:@selector(compare:)];
NSMutableArray *sortedDates= [NSMutableArray arrayWithCapacity:dates.count];
for (NSDate *date in dates)
{
NSString *dateString = [dateFormatter stringFromDate:date];
[sortedDates addObject: dateString];
}

Rajneesh071
- 30,846
- 15
- 61
- 74
-
2You should not use YYYY - "There are two things to note about this example: It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year." – adnako Oct 22 '13 at 07:03
0
- (void)testSortTimeAsString {
NSDictionary *dict1 = @{@"key" : @"none", @"Time" : @"2013-10-01", @"optional" : @"---"};
NSDictionary *dict2 = @{@"key" : @"none", @"Time" : @"2012-12-21", @"optional" : @"---"};
NSDictionary *dict3 = @{@"key" : @"none", @"Time" : @"2013-02-10", @"optional" : @"---"};
NSDictionary *dict4 = @{@"key" : @"none", @"Time" : @"2013-11-25", @"optional" : @"---"};
NSDictionary *dict5 = @{@"key" : @"none", @"Time" : @"2013-06-15", @"optional" : @"---"};
NSArray *array = @[dict1, dict2, dict3, dict4, dict5];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSArray *sorted = [array sortedArrayWithOptions:0 usingComparator:^(id obj1, id obj2) {
NSString *stringDate1 = obj1[@"Time"];
NSString *stringDate2 = obj2[@"Time"];
NSDate *date1 = [dateFormatter dateFromString:stringDate1];
NSDate *date2 = [dateFormatter dateFromString:stringDate2];
NSComparisonResult result = [date1 compare:date2];
return result;
}];
NSLog(@"Sorted array: \n%@", sorted);
}

adnako
- 1,287
- 2
- 20
- 30
0
Sorting dates with that format have the same result as sorting them as strings. So:
NSArray *unordered = @[
@{ @"Time": @"2001-01-01", @"Place" : @"Somewhere" },
@{ @"Time": @"1999-01-01", @"Place" : @"Elsewhere" },
@{ @"Time": @"1999-02-01", @"Place" : @"Nowhere" }
];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Time" ascending:YES selector:@selector(compare:)];
NSArray *ordered = [unordered sortedArrayUsingDescriptors:@[ sortDescriptor ]];
will give you the sorted array.

Tassos
- 3,158
- 24
- 29