Gaby Fitcal
Gaby Fitcal

Reputation: 1944

How to order an array by date?

I have an array with this format:

 <__NSArrayM 0x7fc013d31940>(
        {
            description = "";
            link = "";
            pubDate = "Tue, 16 Jun 2015 07:36:00 +0200";
            title = "";
        },
{
        description = "";
        link = "";
        pubDate = "Mon, 15 Jun 2015 21:18:00 +0200";
        title = "";
    }
        {
            description = "";
            link = "";
            pubDate = "Tue, 16 Jun 2015 11:27:00 +0200";
            title = "";
        },

I want to order it by pudDate. What is the correct way of doing this?

Upvotes: 0

Views: 43

Answers (2)

Paddy
Paddy

Reputation: 764

Check this,

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pubDate" ascending:TRUE];
        [calenderEventsArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

Upvotes: 0

Gralex
Gralex

Reputation: 4485

Something like this:

NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = @"EEE, d MMM yyyy HH:mm:ss ZZZ";
NSArray *newArr = [arr sortedArrayWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = [df dateFromString:obj1[@"pubDate"]];
    NSDate *date2 = [df dateFromString:obj2[@"pubDate"]];
    return [date1 compare:date2];
}];

Use search next time: How to sort an NSMutableArray with custom objects in it?

Upvotes: 4

Related Questions