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
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
}
                        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];
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With