Objective-C排序字符串日期数组

时间:2012-07-07 10:01:53

标签: iphone objective-c ios cocoa-touch ipad

我有一个由日期组成的数组,但是NSString。我该如何排序下降?

编辑:我最后通过调整我的代码来使用NSDate,因为使用其他方法在我的情况下不起作用

2 个答案:

答案 0 :(得分:10)

您可以使用sortedArrayUsingFunction,请考虑以下示例

NSString *str1 = @"03-07-2012";
NSString *str2 = @"01-07-2012";
NSString *str3 = @"02-07-2012";


NSArray *arr = [NSArray arrayWithObjects:str1, str2, str3, nil];
arr = [arr sortedArrayUsingFunction:dateSort context:nil];


//The date sort function
NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];

    NSDate *d1 = [formatter dateFromString:s1];
    NSDate *d2 = [formatter dateFromString:s2];

    return [d1 compare:d2]; // ascending order
    return [d2 compare:d1]; // descending order
}

答案 1 :(得分:2)

将NSString日期隐藏到NSDate对象,而不是基于日期排序数组

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss ZZZ"];

NSDate *date = [dateFormatter dateFromString:dateStr]; 

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
    NSDate *d1 = [NSDate dateWithString:s1];
    NSDate *d2 = [NSDate dateWithString:s2];
    return [d1 compare:d2];
}

NSArray *sorted = [unsorted sortedArrayUsingFunction:dateSort context:nil];