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

Posted

技术标签:

【中文标题】Objective-C 排序字符串日期数组【英文标题】:Objective-C Sort String Date Array [closed] 【发布时间】:2012-07-07 10:01:52 【问题描述】:

我有一个包含日期但为NSString 的数组。如何降序排序?

编辑:我最终调整了我的代码以使用 NSDate,因为在我的情况下使用其他方法不起作用

【问题讨论】:

你有 NSArray of string ?? 是的,我已经尝试过 caseInsensitiveCompare: 方法,但它返回的是升序而不是降序 有什么理由不能使用 NSDate * 吗? 欢迎来到 Stack Overflow!我们希望您尝试自己解决此问题,而不是要求社区为您提供完整的解决方案。当您有一些代码向我们展示证明您所做的一些努力时(即使它是错误的),请更新您的问题并标记以重新打开。谢谢。 【参考方案1】:

你可以使用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

【讨论】:

或遵循相同的想法,因为 caseInsensitiveCompare: 返回预期结果但按升序您可以跳过将字符串格式化为日期并仅返回 [s2 caseInsensitiveCompare:s1] 但它不适用于 1-july-2012、1-jun-2012 等字符串 因此介绍了我的回复。但在那个特定的例子中,这实际上会起作用:)【参考方案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];

【讨论】:

以上是关于Objective-C 排序字符串日期数组的主要内容,如果未能解决你的问题,请参考以下文章

IOS/Objective-C:按字符串中的单词数对 NSStrings 的 NSArray 进行排序

按即将到来的日期对日期为字符串的数组进行排序

对字符串日期数组进行排序

使用 Objective-C 对 int 数组进行排序 - 优化

JS - 将字符串数组作为日期排序

使用日期 Swift 3 对字典数组进行排序