Question

I need to filter search results based on values that were added yesterday. I have seen plenty on finding yesterday using:

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
        [components setHour:-24];
        [components setMinute:0];
        [components setSecond:0];
        NSDate *yesterday = [cal dateByAddingComponents:components toDate:[NSDate date] options:0];
predicate = [NSPredicate predicateWithFormat:@"created_at >= %@", yesterday];

But this finds 24 hours since this exact moment in time. I need to filter yesterday as 12:01am-12:00pm. So the actual 24 hour period that was yesterday.

I'm guessing that I need to do something along the lines of: 1. Take the current date 2. Find the time from the current date to 12:01am of the same day 3. Then subtract 24 hours from that date

I feel confident I can do #3 (and #1 of course), but I'm not sure how to go about #2. I maybe over thinking it but I can't seem to grasp how to say: "Ok, it's 8:03am, I need to remove 8 hours and 2 minutes which will put me at 12:01am".

Was it helpful?

Solution

Start with some date of today, for example "now":

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];

Subtract one day to get some date of yesterday:

NSDateComponents *minusOneDay = [[NSDateComponents alloc] init];
[oneDay setDay:-1];
NSDate *nowMinusOneDay = [cal dateByAddingComponents:minusOneDay toDate:now options:0];

Compute start and end date of the "day calendar unit" that contains yesterday's date:

NSDate *startOfYesterday;
NSTimeInterval lengthOfYesterday;
[cal rangeOfUnit:NSDayCalendarUnit startDate:&startOfYesterday interval:&lengthOfYesterday forDate:nowMinusOneDay];
NSDate *endOfYesterday = [startOfYesterday dateByAddingTimeInterval:lengthOfYesterday];

This should work even if a daylight savings time transition occurs between today and yesterday.

Generally one should avoid to use explicit time intervals such as "24 hours", because not every day has that length.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top