简体   繁体   中英

Sorting NSDate with custom compare function

I have an array of dates. These dates are all NSString objects. Now I want to sort them. This is how my function looks like.

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd-MM-YYYY"];

    NSString *date1 = [NSString stringWithFormat:@"%@",s1];
    NSString *date2 = [NSString stringWithFormat:@"%@",s2];

    NSDate *v1 = [df dateFromString: date1];
    NSDate *v2 = [df dateFromString: date2];
   return [v1 compare:v2];

}

And I call the function like this.

NSArray *sortedKeys = [unsortedKeys sortedArrayUsingFunction:dateSort context:nil];

This is the result

sorted keys are (
    "24-10-2013",
    "28-06-2013",
    "03-10-2013",
    "20-12-2013",
    "04-09-2013",
    "19-09-2013",
    "07-07-2013",
    "15-09-2013",
    "01-07-2013",
    "04-11-2013",
    "27-06-2013",
    "02-10-2013",
    "05-08-2013",
    "17-10-2013",
    "04-10-2013"
)

This is not the correct order, I want them to descending.

Can anybody help me with this?

There are several issues:

  • The correct date format is "dd-MM-yyyy" .
  • To order the dates descending instead of ascending, just replace

     return [v1 compare:v2]; 

    by

     return [v2 compare:v1]; 
  • The stringWithFormat calls are completely unnecessary (as commented by @rmaddy).

  • Creating a date formatter is considered an expensive operation, it should be done only once.

With all that, your compare method should look like this:

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
    static NSDateFormatter *df;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"dd-MM-yyyy"];
    });

    NSDate *v1 = [df dateFromString: s1];
    NSDate *v2 = [df dateFromString: s2];
    return [v2 compare:v1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM