开发者

Sorting issue iphone sdk

Having some problem, I got it sorted but looks likes this,

"10/16/2011 12:00:00 AM",
    "10/16/2011 12:00:00 AM",
    "11/16/2011 12:00:00 AM",
    "11/16/2011 12:00:00 AM",
    "9/15/2011 12:0开发者_运维问答0:00 AM",
    "9/15/2011 12:00:00 AM",
    "9/15/2011 12:00:00 AM"

the format is "MM/dd/yyyy", I want to sort this based on day, then month, then year then time. How can I implement that?

Here is the code

NSSortDescriptor* nameSorter = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSMutableArray *temp = [dateStart mutableCopy];
[temp sortUsingDescriptors:[NSArray arrayWithObject:nameSorter]];
dateStart = temp;
NSLog(@"Sorted: %@",dateStart);


You can use NSDateFormatter to convert the string into NSDate and Comparator to compare them,

NSArray *datesArray = @[@"10/16/2011 12:00:00 AM",
                   @"10/16/2011 12:00:00 AM",
                   @"11/16/2011 12:00:00 AM",
                   @"11/16/2011 12:00:00 AM",
                   @"9/15/2011 12:00:00 AM",
                   @"9/15/2011 12:00:00 AM",
                   @"9/15/2011 12:00:00 AM"];

NSLog(@"dates:%@", datesArray);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];

NSArray *sortedDatesArray = [datesArray sortedArrayUsingComparator:^(id obj1, id obj2){

    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];

    return [date1 compare:date2];

}];

NSLog(@"%@",sortedDatesArray);



Output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜