我打算写一个日期过滤器。
NSMutableArray *muarray = @[
@"2019/6",
@"2019/5",
@"2019/4",
@"2019/3",
@"2019/2",
@"2019/1",
@"2018/12",
@"2018/11",
@"2018/10",
@"2018/9",
@"2018/8",
@"2018/7",
@"2018/6",
@"2018/5",
@"2018/4",
@"2018/3",
@"2018/2",
@"2018/1",
@"2017/12",
@"2017/11",
@"2017/10",
@"2017/9",
@"2017/8",
@"2017/7",
@"2017/6",
@"2017/5",
@"2017/4",
@"2017/3",
@"2017/2",
@"2017/1"
].mutableCopy;
NSString *tempStr = [NSString stringWithFormat:@"self between {\'%@\',\'%@\'}", @"2017/8", @"2018/8"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:tempStr];
[muarray filterUsingPredicate:predicate];
我想将项目从“ 2017/8”过滤到“ 2018/8”。 我的代码不起作用。如何解决?
答案 0 :(得分:0)
首先,您需要将NSString
的数组转换为NSDate
的数组才能使用NSDate
进行过滤。请使用下面的代码来满足您的要求。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy/MM"];
NSMutableArray *muarray = @[
@"2019/6",@"2019/5",@"2019/4",@"2019/3",@"2019/2",@"2019/1",@"2018/12",@"2018/11",@"2018/10",@"2018/9",@"2018/8",@"2018/7",@"2018/6",@"2018/5",@"2018/4",@"2018/3",@"2018/2",@"2018/1",@"2017/12",@"2017/11",@"2017/10",@"2017/9",@"2017/8",@"2017/7",@"2017/6",@"2017/5",@"2017/4",@"2017/3",@"2017/2",@"2017/1"
].mutableCopy;
NSMutableArray* aryDates = [NSMutableArray new];
for (NSString* strDate in muarray) {
NSDate *dateFromString = [dateFormatter dateFromString:strDate];
[aryDates addObject:dateFromString];
}
NSDate* date1 = [dateFormatter dateFromString:@"2017/8"];
NSDate* date2 = [dateFormatter dateFromString:@"2018/8"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BETWEEN %@", [NSArray arrayWithObjects:date1, date2, nil]];
[aryDates filterUsingPredicate:predicate];
NSLog(@"%@",aryDates);