demo地址:https://share.weiyun.com/5KdP6lw
创建一个类SortedTime
继承于NSObject
在该类中有一个方法,对传入字符串数组中的时间字符串根据时间格式进行排序(升序/降序)
+ (NSMutableArray *)sortedTimeWithTimeArray:(NSMutableArray<NSString *> *)timeArray dateFormater:(NSString *)dateFormater ascending:(BOOL)ascending;
创建一个类CustomDate
,继承于NSObject
,该类中有两个属性
@property (nonatomic, strong) NSString *strTime;
@property (nonatomic, strong) NSDate *dateTime;
在SortedTime.m
中,该方法的实现:
+ (NSMutableArray *)sortedTimeWithTimeArray:(NSMutableArray<NSString *> *)timeArray dateFormater:(NSString *)dateFormater ascending:(BOOL)ascending
{
NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
NSMutableArray *arrResult = [[NSMutableArray alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
[formatter setTimeZone:timeZone];
for (NSString *timeString in timeArray)
{
CustomDate *dateC = [[CustomDate alloc] init];
[formatter setDateFormat: dateFormater];
dateC.dateTime = [formatter dateFromString:timeString];
dateC.strTime = timeString;
[arrTemp addObject:dateC];
}
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"dateTime" ascending:ascending];
NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:&sorter count:1];
NSMutableArray *sortArray = [arrTemp sortedArrayUsingDescriptors:sortDescriptors].mutableCopy;
for (CustomDate *dateCustom in sortArray)
{
[arrResult addObject:dateCustom.strTime];
}
return arrResult;
}
关于NSSortDescriptor
的使用,可以参考链接:
https://www.jianshu.com/p/3e9f0884be6b
使用方法:
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *arrTest = [[NSMutableArray alloc] init];
[arrTest addObject:@"2018-11-20"];
[arrTest addObject:@"2018-11-19"];
[arrTest addObject:@"2018-11-7"];
[arrTest addObject:@"2018-5-15"];
NSLog(@"%@",[SortedTime sortedTimeWithTimeArray:arrTest dateFormater:@"yyyy-M-d" ascending:YES]);
}
输出结果:
(
"2018-5-15",
"2018-11-7",
"2018-11-19",
"2018-11-20"
)
*注:时间的格式要传正确,且时间不能重复,否则可能导致排序失败