avinash
avinash

Reputation: 611

how to select last 3 month via using NSPredicate and NSDate

For example, for any date in February you would calculate Data using the records with a month of November, December, and January.

Thanx....

Upvotes: 3

Views: 774

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90117

You have to use some NSCalendar and NSDateComponents magic. I hope the comments are enough to understand what the code does.

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];

For today (February 6, 2012) this will return all objects with dates between November 1, 2011 12:00:00 AM and January 31, 2012 11:59:59 PM.

Upvotes: 3

Related Questions