1

I know how to filter an array or set of fetchedResults by date ranges. How can filter by time of day as in 3PM to 5PM.

Some answers on SO say you can't do this for a SQLLite backed MOC and have to fetch all the results and filter. However, I can't figure out how to filter.

You can filter for 3PM to 5PM on a specific day using:

NSCalendar *myCal = [NSCalendar currentCalendar];
    myCal.timeZone = [NSTimeZone localTimeZone];
    NSDate *startOfDay = [myCal startOfDayForDate:[NSDate date]];
    NSDate *noon = [myCal dateByAddingUnit:NSCalendarUnitHour
                                        value:12
                                       toDate:startOfDay
                                      options:0];


    NSDate *threepm = [myCal dateByAddingUnit:NSCalendarUnitHour
                                       value:15
                                      toDate:startOfDay
                                     options:0];

     NSPredicate *fivepmPred = [NSPredicate predicateWithFormat:@"starttime <= %@", fivepm];
  NSPredicate *threepmPred = [NSPredicate predicateWithFormat:@"starttime >= %@", threepm];
NSMutableArray *subPredicates = [NSMutableArray arrayWithCapacity:10];
    [subPredicates addObject:fivepmPred];
    [subPredicates addObject:threePred];

But how do you filter a set of results over a month or so for 3PM to 5PM independent of the day

Thanks in advance for any ideas.

user1904273
  • 4,562
  • 11
  • 45
  • 96
  • 1
    If you really are filtering an array, and not on a fetch request (which is harder, and might need others things, as you saw on other SO questions), you just can use a NSPredicate with block. – Larme Jan 20 '19 at 18:29
  • 1
    And example on how to construct it: https://stackoverflow.com/questions/38623592/nspredicate-with-nsdate-filtering-by-day-month-but-not-year?rq=1 – Larme Jan 20 '19 at 18:47
  • Elegant approach using the block. Will try it out. – user1904273 Jan 22 '19 at 22:00

0 Answers0