NSPredicate to filter between two dates of NSString type

佐手、 提交于 2019-12-03 20:34:46

You need to change your datatype to date (what even makes most sense here). Your tests pass by time, cause they exactly match one string and your predicate contains equals. So if you would just query for < and > no result would be returned in each "test"

Then your snippet

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Date >=  %@ AND
Date <=  %@", startDate,endDate];

NSArray *filter = [arrayEvents filteredArrayUsingPredicate:predicate];

works as expected. There is no way to do that with strings as it would require a date formatter to parse the date from the string and compare that. This would be absolutely inefficient. So if you really want to filter this, create a instance of NSDateFormatter and run through each Dictionary. Grab out the date and compare that new formatted date to your start and end date. If it is in between add it to the result array (also need to create this before).

NSMutableArray* result = [NSMutableArray array];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd/MM/yy";
for (NSDictionary *dict in yourArray) {
    NSString *dateString = dict[@"Date"];
    NSDate *date = [formatter dateFromString:dateString];
    if ([date compare:startDate] > 0 && [date compare:endDate] < 0) {
       [result add:dict];
    }
}

//use the filtered array here

I've not used NSPredicate much but the concept of comparison of dates within strings is almost certainly not supported. If you use the right type to represent your data then you will have more success I'm sure. The right data type being NSDate.

You cannot compare two strings like that. You can use timestamp instead of String then you can compare the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!