Вы должны использовать магию NSCalendar
и NSDateComponents
. Я надеюсь, что комментариев достаточно, чтобы понять, что делает код.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today = [NSDate date];
// components for "3 months ago"
NSDateComponents *dateOffset = [[NSDateComponents alloc] init];
[dateOffset setMonth:-3];
// date on "today minus 3 months"
NSDate *threeMonthsAgo = [calendar dateByAddingComponents:dateOffset toDate:today options:0];
// only use month and year component to create a date at the beginning of the month
NSDateComponents *threeMonthsAgoComponents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit fromDate:threeMonthsAgo];
threeMonthsAgo = [calendar dateFromComponents:threeMonthsAgoComponents];
// you need the next 3 months
[dateOffset setMonth:3];
// calculate from the beginning of the month
NSDate *lastMonth = [calendar dateByAddingComponents:dateOffset toDate:threeMonthsAgo options:0];
// get dates that are _on_ or _after_ the first date and _before_ the second date
NSPredicate *datePredicate = [NSPredicate predicateWithFormat:@"date >= %@ && date < %@", threeMonthsAgo, lastMonth];
На сегодня (6 февраля 2012 г.) будут возвращены все объекты с датами между 1 ноября 2011 г., 12:00:00 и 31 января 2012 г., 23:59:59.