简体   繁体   中英

How to sort an NSArray of strings in date format @“Aug 2013” in ascending order..?

I have an array of NSString objects in the format... @"Aug 2013" @"July 2013" and so on...

I want to sort this array in ascending order .. Is getting the date first for individual value a good idea..?

An other solution in one block

NSArray* array = [NSArray arrayWithObjects:@"Janvier 2012",@"Mars 2013", @"Juin 2013", @"Octobre 2012", nil];

NSArray* result = [array sortedArrayUsingComparator:^(id a, id b) {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM YYYY"];

    NSDate* datea = [dateFormat dateFromString:a];
    NSDate* dateb = [dateFormat dateFromString:b];

    return [datea compare:dateb];
}];

I see you prefer "stringly" (not a typo) typed variables. They often end up giving you error like this. What you really should do is to store dates as dates. They compare nicely agains each other and you can do fancy date calculations with them. The same is true for numbers.

Then if you want to present them like "Aug 2013" or "July 2013" in the user interface: use a date formatter to format the dates into appropriate strings for display only .


For this case the two main classes that you should look into (read the documentation and such) are: NSDate and NSDateFormatter . NSCalendar and NSDateComponents should also prove useful.

I address this kind of problem by using a category to switch back and forth between NSDate and NSString. I would solve this problem by converting to dates using the category, sorting, and then converting back.

My category looks like the following (you'd need to add similar methods to manage the month/year format that your strings have)

    #import "NSDate+Utils.h"


    @implementation NSDate (NSDate_Utils)

    + (NSDate *)dateFromI18NString:(NSString *)dateString
    {
        if (dateString == nil)
            return nil;
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
        NSDate *d = [dateFormatter dateFromString:dateString];
        return d;
    }

    - (NSString *)dateToI18NString
    {
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";

        return [dateFormatter stringFromDate:self];

    }

我会使用NSArrayNSDate对象,并在需要时格式化它的内容。

You can sort your array by implement below code.

-(void)somemethod{
   NSArray *sortedArray = [[NSArray alloc]initWithArray:YOURARRAY];
   sortedArray = [sortedArray sortedArrayUsingFunction:dateSort context:nil];
  }       

Call below function as above to sort your array.(Update formater as per your date format of array )

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM yyyy"];

NSDate *d1 = [formatter dateFromString:s1];
NSDate *d2 = [formatter dateFromString:s2];

return [d1 compare:d2]; // ascending order
return [d2 compare:d1]; // descending order
}

I hope, It may help you.

Try this

- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *unsortedArray =[[NSArray alloc]initWithObjects:@"July 2013",@"Aug 2013",@"Jun 2012", nil];
NSMutableArray *arrSorted = [NSMutableArray arrayWithArray:unsortedArray];
for(int i=0;i<[arrSorted count];i++)
{

    for(int j=i+1;j<[arrSorted count];j++)
    {
        NSDateFormatter *df=[[NSDateFormatter alloc] init];
        df.dateFormat=@"MMM yyyy";
        NSDate *date1=[df dateFromString:[arrSorted objectAtIndex:i]];
        NSDate *date2=[df dateFromString:[arrSorted objectAtIndex:j]];
        if([date1 compare:date2]== NSOrderedAscending)
        {
            [arrSorted exchangeObjectAtIndex:i withObjectAtIndex:j];
        }
    }
}
// ORDER_DESCEND
NSLog(@"%@",arrSorted);

arrSorted = [NSMutableArray arrayWithArray:[[arrSorted reverseObjectEnumerator] allObjects]];
// ORDER_ASCEND
NSLog(@"%@",arrSorted);

}
- (NSArray *)sortedDateArrayWithExistedArray:(NSMutableArray *) setExistedArray acending:(BOOL)ascendingBoolvalue
{

    NSArray *sortedArray = [setExistedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"dd MMM, yyyy"];

            NSDate *d1 = [formatter dateFromString:obj1[@"displayDate"]];
            NSDate *d2 = [formatter dateFromString:obj2[@"displayDate"]];
       // id =  [d1 compare:d2];
        if (ascendingBoolvalue)
        {
            return [d1 compare:d2];
        }
        else
        {
            return [d2 compare:d1];
        }
    }];

     return sortedArray;
}

set setExistedArray == yourArray set ascending parameter as yes or no based upon your requirement yes for ascending order no for descending order.

how to access this function

self.sortedArray = [[self sortedDateArrayWithExistedArray:self.yourArray Acending:NO] mutableCopy];

if yourArray is mutable place call mutable copy method otherwise no need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM