使用日期格式对 NSArray 进行排序

sorting the NSArray using date format

但是我没有得到当前输出,我想用日期格式对数组进行排序,我的数组日期是字符串format.that数据是这样的

( 周五,4 月 10 日,下午 16:59, 周五,4 月 10 日,下午 18:37, 周五,4 月 10 日,下午 22:28, 星期六,4 月 11 日,下午 16:59 )

所以我想正确排序这些数据

首先重新检查您的日期格式。使用 "EE,dd MMM,HH:mm" 或 "EE,dd MMM,hh:mm a".

然后你可以像这样对数组进行排序,

- (void)sortDateStrings {

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"EE,dd MMM,HH:mm"];

  // Input
  NSArray *dateStringArray = [NSArray arrayWithObjects:@"Fri,10 Apr,22:28", @"Sat,11 Apr,16:59", @"Fri,10 Apr,16:59", @"Fri,10 Apr,18:37", nil];

  NSArray *sortedArray = [dateStringArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    NSDate *date1 = [formatter dateFromString:obj1];
    NSDate *date2 = [formatter dateFromString:obj2];

    return [date1 compare:date2];
  }];

  NSLog(@"Original = %@", dateStringArray);
  NSLog(@"Sorted = %@", sortedArray);
}

试试这个 -

NSString *str1 = @"Fri,10 Apr,16:59";
NSString *str2 = @"Fri,10 Apr,14:37";
NSString *str3 = @"Sat,11 Apr,16:59";    

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:@"EE,dd MMM,HH:mm"];

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

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

查看结果截图-

你可以试试这个:

NSArray *arrOfDates = [NSArray arrayWithObjects:@"Fri,10 Apr,16:59", @"Fri,10 Apr,18:37", @"Fri,10 Apr,22:28", @"Sat,11 Apr,16:59", nil];
NSMutableArray *arrOfSortedDates = [[NSMutableArray alloc]init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEE,dd MMM,HH:mm"];
for(NSString *strDate in arrOfDates){
    NSDate *formattedDate = [formatter dateFromString:strDate];
    [arrOfSortedDates addObject:formattedDate];
}

[arrOfSortedDates sortUsingSelector:@selector(compare:)];