我有一个数组,其中包含以字符串表示的日期列表:
NSMutableArray *objArray=[[NSMutableArray alloc]init];
[objArray addObject:@"18-01-2013 2:51"];
[objArray addObject:@"16-01-2013 5:31"];
[objArray addObject:@"15-01-2013 3:51"];
[objArray addObject:@"17-01-2013 4:41"];
[objArray addObject:@"03-02-2013 3:21"];
[objArray addObject:@"05-01-2013 3:01"];
请告诉我如何使用日期按升序排列此数组。
最佳答案
NSDateFormatter * formatter = [[[[NSDateFormatter alloc] init] autorelease];
[格式化程序setDateFormat:@“dd-MM-yyyy hh:mm”];
NSComparator compareDates = ^(id string1, id string2)
{
NSDate *date1 = [formatter dateFromString:string1];
NSDate *date2 = [formatter dateFromString:string2];
return [date1 compare:date2];
};
NSSortDescriptor * sortDesc = [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO comparator:compareDates]autorelease];
[objArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
通过使用此代码,我得到了准确的输出,谢谢大家
关于iphone - 如何以升序比较包含日期的NSStrings数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14722047/