iosobjective-csortingnsarray

iOS sort an NSArray of Time NSString's


I need to sort an NSArray containing time NSString's such as,

NSMutableArray *times = [[NSMutableArray alloc]initWithObjects:@"09:00 AM",@"07:30 AM",@"06:45 PM",@"05:00 PM",@"12:45 AM",@"12:45 PM",@"01:00 AM",@"01:15 PM", nil];

What I need is to sort the array in ascending order of time.
Is there any way to do such a thing?


Solution

  • NSMutableArray *times = [[NSMutableArray alloc]initWithObjects:@"09:00 AM",@"07:30 AM",@"06:45 PM",@"05:00 PM",@"12:45 AM",@"12:45 PM",@"01:00 AM",@"01:15 PM", nil];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    
    NSArray *sortedTimes = [times sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
    {
        NSDate *date1 = [dateFormatter dateFromString:obj1];
        NSDate *date2 = [dateFormatter dateFromString:obj2];
        return [date1 compare:date2];
    }];
    

    optimized version:

    NSMutableArray *times = [[NSMutableArray alloc]initWithObjects:@"09:00 AM",@"07:30 AM",@"06:45 PM",@"05:00 PM",@"12:45 AM",@"12:45 PM",@"01:00 AM",@"01:15 PM", nil];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    
    NSMutableArray *dates = [NSMutableArray arrayWithCapacity:times.count];
    for (NSString *timeString in times)
    {
        NSDate *date = [dateFormatter dateFromString:timeString];
        [dates addObject:date];
    }
    
    [dates sortUsingSelector:@selector(compare:)];
    
    NSMutableArray *sortedTimes = [NSMutableArray arrayWithCapacity:dates.count];
    for (NSDate *date in dates)
    {
        NSString *timeString = [dateFormatter stringFromDate:date];
        [sortedTimes addObject:timeString];
    }