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

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

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

【问题讨论】:

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

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


【解决方案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];

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 2015-06-03
    • 2015-08-21
    • 1970-01-01
    • 2016-08-07
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多