例如,对于 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 到 2012 年 1 月 31 日下午 11:59:59 之间的所有对象。
关于iphone - 如何通过使用 NSPredicate 和 NSDate 选择最近 3 个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9156204/