在 objective c 中按日期月份和年份对日期数组进行排序
Sort array of dates with date month and year in objective c
我想用日期对数组进行排序,但日期只按日期和月份排序,而不按年份排序我的代码:
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];
}];
它没有按日期正确排序。
问题是 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];
}];
好像打错了。
请将代码替换为
NSDate *d2 = [appSharedData.CommanFormatForConditional dateFromString: [obj2 objectForKey:@"scheduleStart"]];
我想用日期对数组进行排序,但日期只按日期和月份排序,而不按年份排序我的代码:
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];
}];
它没有按日期正确排序。
问题是 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];
}];
好像打错了。
请将代码替换为
NSDate *d2 = [appSharedData.CommanFormatForConditional dateFromString: [obj2 objectForKey:@"scheduleStart"]];