3

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

像这样的东西:

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

4

1 回答 1

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

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

[NSPredicate predicateWithFormat:@"date >= %@ AND date < %@", beginningOfCurrentMonth, beginningOfNextMonth];
于 2012-11-07T03:34:11.283 回答