Search code examples
iphonensmutablearraydate-sorting

How to sort the array that contains dates in iphone sdk


I have an array that contains date strings like

"9/15/2011 12:00:00 AM", "10/15/2011 12:00:00 AM", "11/16/2011 12:00:00 AM"

How can I sort this array in descending order? The order should be, sort by year first, then, month, then date and then time.

Please share your ideas. Thank you


Solution

  • Sorting NSDates while they are in NSString format is almost not possible, except if they are in the format "YYYYMMddHHmmss" which you can sort as sorting strings. Refer @Daniel R Hicks answer.

    Convert the string into NSDate while you parse and add the dates from web service.

    NSString *dateStr = ...
    NSDateFormatter *df = ;[NSDateFormatter alloc] init];
    [df setDateFormat:@"M/dd/YYYY hh:mm:ss a"];
    
    [datesArray addObject:[df dateFromString:dateStr]];
    

    And the sorting,

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

    And the original answer is here!