Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Sort String Date Array [closed]

I have an array which consists of dates but as NSString. How do I sort it descending?

EDIT : I Ended up by tweaking my code to use NSDate as using other methods won't work in my case

like image 246
Mohamed Elzarei Avatar asked Dec 13 '22 00:12

Mohamed Elzarei


2 Answers

You could use sortedArrayUsingFunction, consider the bellow example

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
}
like image 200
Omar Abdelhafith Avatar answered Dec 14 '22 22:12

Omar Abdelhafith


Covert NSString date to NSDate object and than sort array based on date

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];
like image 27
msk Avatar answered Dec 14 '22 23:12

msk