开发者

How to sort NSArray with date time values?

I have an NSArray containing date/time NSStrings in the following format:

2/2/2011开发者_如何学JAVA 2:46:39 PM
2/4/2011 11:59:47 AM
…

where the date is represented as month/day/year.

How do I sort this NSArray making sure the newest date/times are at the top?


When you’re dealing with dates, use NSDate instead of NSString. Also, it’s important to consider the time zone — does the Web service provide dates in UTC or some other time zone?

You should first convert your array of strings into an array of dates. Otherwise, you’d be converting a string to a date whenever it is used for comparison, and there will be more comparisons than the number of strings.

For example:

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MM/DD/YYYY hh:mm:ss a"];

NSMutableArray *dateArray = [NSMutableArray array];
for (NSString *dateString in array) {
    NSDate *date = [formatter dateFromString:dateString];
    if (date) [dateArray addObject:date];
    // If the date is nil, the string wasn't a valid date.
    // You could add some error reporting in that case.
}

This converts array, an array of NSStrings, to dateArray, a mutable array of NSDates. The date formatter uses the system time zone. If you want to use UTC as the time zone:

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MM/DD/YYYY hh:mm:ss a"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

Having done that, sorting the array is trivial:

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


Use method compare to compare two dates,

Sample NSDate comparision,

NSDate *dateOne = [NSDate dateWithString:@"2008-12-04 03:00:00 +0900"];
NSDate *dateTwo = [NSDate dateWithString:@"2008-12-04 04:00:00 +0900"];

switch ([dateOne compare:dateTwo]){
case NSOrderedAscending:
NSLog(@”NSOrderedAscending”);
break;
case NSOrderedSame:
NSLog(@”NSOrderedSame”);
break;
case NSOrderedDescending:
NSLog(@”NSOrderedDescending”);
break;
}

Use you own logic to sort


use this

    NSMutableArray *mutArr=[yourArray mutableCopy];//convert your NSArray into mutable array
    NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorealese];
    [df setDateFormat:@"MM/DD/YYYY hh:mm:ss a"];
    NSDate *compareDate;
NSInteger index;
for(int i=0;i<[mutArray count];i++)
{
    index=i;
    compareDate=[df dateFromString:[mutArray objectAtIndex:i]];
    NSDate *compareDateSecond;
    for(int j=i+1;j<counter;j++)
    {
        compareDateSecond=[df dateFromString:[mutArr objectAtIndex:j]];
        NSComparisonResult result = [compareDate compare:compareDateSecond];
       if(result == NSOrderedAscending)
       {
           compareDate=compareDateSecond;
           index=j;
       }
    }
    if(i!=index)
      [mutArr exchangeObjectAtIndex:i withObjectAtIndex:index];
}
    }

NSLog(@"%@",mutArr);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜