例如,对于2月中的任何日期,您将使用11月,12月和1月月份的记录来计算数据。
谢谢...
最佳答案
您必须使用一些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];
对于今天(2012年2月6日),它将返回日期在2011年11月1日12:00:00 AM和2012年1月31日11:59:59 PM之间的所有对象。
关于iphone - 如何通过使用NSPredicate和NSDate选择最近3个月,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9156204/