如何使用NSDate在一个月内构建NSPredicate过滤?

Seb*_*ian 3 iphone objective-c nsdate nspredicate ios

有没有办法一般地在一个月内获得所有日子?

像这样的东西:

[NSPredicate predicatewithFormat@"(date.firstDayOfMonth >= @)AND(date.lastDayOfMonth <= @)"];

Dav*_*ong 12

是.你需要弄清楚这个月的第一个瞬间是什么,以及下个月的第一个瞬间.我是这样做的:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *nowComponents = [calendar components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];
[nowComponents setDay:1];

NSDate *beginningOfCurrentMonth = [calendar dateFromComponents:nowComponents];

NSDateComponents *oneMonth = [[NSDateComponents alloc] init];
[oneMonth setMonth:1];

NSDate *beginningOfNextMonth = [calendar dateByAddingComponents:oneMonth toDate:beginningOfCurrentMonth options:0];
Run Code Online (Sandbox Code Playgroud)

一旦你有了这两个NSDate,那么你可以这样做:

[NSPredicate predicateWithFormat:@"date >= %@ AND date < %@", beginningOfCurrentMonth, beginningOfNextMonth];
Run Code Online (Sandbox Code Playgroud)