0

In my application I have an array of strings representing the dates in the Format MM/dd/YYYY

and below is the code I used to sort this array

NSDateFormatter *formatter =[[NSDateFormatter alloc]init];

[formatter setDateFormat:@"MM/dd/YYYY"];
NSLog(@" arr %@",arr);
[arr sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
 {

     NSDate *date1=[formatter dateFromString:obj1];
     NSDate *date2=[formatter dateFromString:obj2];
     return [date1 compare:date2];
 }];
NSLog(@" arr %@",arr);

below is the output of nslog

2013-04-08 17:23:48.112 SEEMR[2792:c07]  arr (
    "02/18/2013",
    "02/16/2013",
    "02/14/2013",
    "01/16/2013",
    "02/13/2013",
    "03/16/2013"
)
2013-04-08 17:24:07.662 SEEMR[2792:c07]  arr (
    "02/18/2013",
    "02/16/2013",
    "02/14/2013",
    "01/16/2013",
    "02/13/2013",
    "03/16/2013"
)

But it is not sorting as expected so help me peers

2
  • 1
    for sorting date your date should be in yyyy/MM/dd format for correct sorting Commented Apr 8, 2013 at 12:05
  • 1
    [datearray sortUsingSelector:@selector(compare:)]; with date time format yyyy-MM-dd Commented Apr 8, 2013 at 12:07

2 Answers 2

4

When using NSDateFormatter, always test if your formatting string is correct. Yours isn't. It should be MM/dd/yyyy (the case is important).

In other words, since your formatter works incorrectly, all dateFromString: return nil and you are always comparing nil with a nil, which returns 0.

Saving your dates as a NSDate instances would make your life easier. In general, it's better to convert the date into NSString only if you are presenting it to the user or sending it to some other application (e.g. web service).

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this:

NSSortDescriptor* sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"date property name" ascending:YES];
[mutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];

Hope it helps!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.