iphone - 如何通过使用 NSPredicate 和 NSDate 选择最近 3 个月

标签 iphone core-data nspredicate

例如,对于 2 月的任何日期,您将使用 11 月、12 月和 1 月的记录来计算数据。

谢谢....

最佳答案

你必须使用一些NSCalendarNSDateComponents魔法。我希望这些注释足以理解代码的作用。

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/

相关文章:

ios - 复杂的 NSPredicates : comparing values on the most-recent object

iphone - 用户界面自动化 : Failed to authorize rights with status: -60007

iphone - 核心数据保存崩溃

ios - 使用 Realm 搜索数组 (iOS)

ios - ALAssets 的 NSPredicate 和 NSArray

ios - iOS 7 上的核心数据迁移属性偏移

iphone - 仅在 UIImageView 的非透明像素上有效地检测触摸

iphone - UINavigationBar UIBarButtonItems 单击区域比所需的大得多

iphone - 如何获得精确的时间,例如 Objective-C 中的毫秒数?

arrays - 在 CoreData 中使用单个实体时如何持久重新排序项目?