本文介绍了排序包含日期作为字符串的字典的NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想基于Date参数对以下数组进行排序,但是问题出在服务器上,我没有得到timestamp
,我得到的日期是string
,有人可以帮忙吗.
I want to sort the following array based on the Date parameter but the problem is from a server I am not getting a timestamp
, I am getting the date as a string
, can anyone please help.
NSArray *array = @[
@{@"valid":@"Y",@"mof":@"ON",@"dof":@"17-05-2019",@"rtntype":@"CODE1",@"ret_prd":@"042019"},
@{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE1",@"ret_prd":@"032019"},
@{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE2",@"ret_prd":@"032019"}
];
我已尝试应用该解决方案,但由于我们拥有的日期在NSString
中,而不在NSDate
或NSTimeInterval
I have tried applying the solution but it won't work as the Date we have is in NSString
and not in NSDate
or NSTimeInterval
[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue] == [obj2 doubleValue])
return NSOrderedSame;
else if ([obj1 intValue] < [obj2 doubleValue])
return NSOrderedAscending;
else
return NSOrderedDescending;
}];
推荐答案
我假设您有一个特定的原因来按原样保留数据,而不是解析为模型类以方便使用.
I am assuming you have a specific reason to keep data as it is instead of parsing into model class keep it handy.
在您的情况下,您可以尝试使用以下代码对数组进行排序:
In your scenario you could try the following code to sort the array:
NSArray *array = @[
@{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE1",@"ret_prd":@"032019"},
@{@"valid":@"Y",@"mof":@"ON",@"dof":@"17-05-2019",@"rtntype":@"CODE1",@"ret_prd":@"042019"},
@{@"valid":@"Y",@"mof":@"ON",@"dof":@"19-04-2019",@"rtntype":@"CODE2",@"ret_prd":@"032019"}
];
//NSDateFormatter to convert NSString to NSDate
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
if ([obj1 isKindOfClass:[NSDictionary class]]
&& [obj2 isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict1 = (NSDictionary *)obj1;
NSDictionary *dict2 = (NSDictionary *)obj2;
if ([dict1[@"dof"] isKindOfClass:[NSString class]]
&& [dict2[@"dof"] isKindOfClass:[NSString class]]) {
NSString *dof1 = (NSString *) dict1[@"dof"];
NSString *dof2 = (NSString *) dict2[@"dof"];
NSDate *date1 = [formatter dateFromString:dof1];
NSDate *date2 = [formatter dateFromString:dof2];
return [date1 compare:date2];//Update the return based on in which order you want the resulting array
}
}
return NSOrderedSame;
}];
NSLog(@"%@", sortedArray);
结果是:
(
{
dof = "19-04-2019";
mof = ON;
"ret_prd" = 032019;
rtntype = CODE1;
valid = Y;
},
{
dof = "19-04-2019";
mof = ON;
"ret_prd" = 032019;
rtntype = CODE2;
valid = Y;
},
{
dof = "17-05-2019";
mof = ON;
"ret_prd" = 042019;
rtntype = CODE1;
valid = Y;
}
)
这篇关于排序包含日期作为字符串的字典的NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!