i have date string in form of "yyyy-MM-dd HH:mm" i have some 100 obhjects in an array with different date and time.now my question is how to sort this array based on time and date, i tried in many ways but no use .can any one help me .thanks in advance
            Asked
            
        
        
            Active
            
        
            Viewed 915 times
        
    -1
            
            
        - 
                    1http://stackoverflow.com/questions/28711360/how-to-sort-the-array-that-contains-date-in-strings-in-ascending-order------ or --------- http://stackoverflow.com/questions/1132806/sort-nsarray-of-date-strings-or-objects.. – Er.Shreyansh Shah Feb 25 '15 at 05:24
- 
                    Check out the NSDate [comp](http://stackoverflow.com/questions/9781467/nsdate-comparing-two-dates) method – nikhil84 Feb 25 '15 at 05:25
- 
                    Do you mean you have dates in string format? Or do you mean you have NSDate objects? – David Berry Feb 25 '15 at 07:11
2 Answers
0
            
            
        used this method for sort an array.
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortArrayUsingDescriptors:@[sortDescriptor]];
May be help for you
 
    
    
        SGDev
        
- 2,256
- 2
- 13
- 29
- 
                    i want to sort array based on time and date i want to sort latest one – Ravikiran Gajula Feb 25 '15 at 05:59
- 
                    Is above code not sort you date array? I am using same approach and it will work for me. – SGDev Feb 25 '15 at 06:05
0
            
            
        If you have an array of strings, take advantage of your date format and just sort it lexically.
NSArray* sorted = [dates sortedArrayUsingComparator:^(NSString* a, NSString* b) {
    return [a compare:b];
}];
If you actually have an array of NSDate objects, use the NSDate compare functions, using almost identical code (compare: works to compare two homogenous data types in many cases)
NSArray* sorted = [dates sortedArrayUsingComparator:(NSDate* a, NSDate* b) {
    return [a compare:b];
}];
With the simplicity of the comparator, you can actually just use the selector directly:
NSArray* sorted = [dates sortedArrayUsingSelector:@selector(compare:)];
 
    
    
        David Berry
        
- 40,941
- 12
- 84
- 95
