如何排序字符串格式,如" 2013-10-09"

时间:2013-10-22 06:40:04

标签: ios ios6 nsstring ios7

我有一个包含NSDictionary对象的数组,其中一个键是Time,其中包含时间字符串格式,如“2013-10-09”,我需要按时间键对数组进行排序,但我不知道如何用这种格式对NSString进行排序。

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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);
}

答案 2 :(得分:0)

使用该格式对日期进行排序与​​将它们排序为字符串具有相同的结果。 所以:

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

将为您提供已排序的数组。