在目标c中用日期月份和年份对日期数组进行排序

时间:2019-03-07 09:35:16

标签: ios objective-c nsdateformatter

我想对带有日期的数组进行排序,但是日期仅对日期和月份进行排序,而不对年份进行排序:

NSArray *sortedArray = [arrClassSehedule sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *d1 = [appSharedData.CommanFormatForConditional dateFromString: [obj1 objectForKey:@"scheduleStart"]];
    NSDate *d2 = [appSharedData.CommanFormatForConditional dateFromString: [obj1 objectForKey:@"scheduleStart"]];
    return [d1 compare: d2];
}];

按日期排序不正确。

2 个答案:

答案 0 :(得分:0)

问题出在d1上,您正在使用obj1,而d2上,您也在使用obj1。所以就像Lal Krishna所说的错字。这是固定版本:

NSArray *sortedArray = [arrClassSehedule sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *d1 = [appSharedData.CommanFormatForConditional dateFromString:[obj1 objectForKey:@"scheduleStart"]];
    NSDate *d2 = [appSharedData.CommanFormatForConditional dateFromString:[obj2 objectForKey:@"scheduleStart"]];
    return [d1 compare:d2];
}];

答案 1 :(得分:0)

好像是错字。

请使用以下代码替换

 NSDate *d2 = [appSharedData.CommanFormatForConditional dateFromString: [obj2 objectForKey:@"scheduleStart"]];