我想根据时间的AM和PM值排序数组...
我得到的反应如下:
(
{
Rate = "4.44";
Count = 3;
Hours = "04:00 PM";
},
{
Rate = "5.55";
Count = 5;
Hours = "07:00 AM";
},
{
Rate = "3.33";
Count = 2;
Hours = "08:00 PM";
}
)
我希望按照上午和下午的时间对时间进行排序。
答案 0 :(得分:3)
首先需要将Hours字符串转换为类NSDate
的对象:
NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"hh:mm a";
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *dateA = [df dateFromString:[a objectForKey:@"Hours"]];
NSDate *dateB = [df dateFromString:[b objectForKey:@"Hours"]];
return [dateA compare:dateB];
}];
答案 1 :(得分:0)
可能是这个帮助你...
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];
}];
优化版:
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];
}