问题
Is there a way to get all days in a month generically ?
Something like this:
[NSPredicate predicatewithFormat@"(date.firstDayOfMonth >= @)AND(date.lastDayOfMonth <= @)"];
回答1:
Yes. You need to figure out what the first instant of the month is, as well as the first instant of the next month. Here's how I would do it:
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];
Once you've got those two NSDate
s, then you can do:
[NSPredicate predicateWithFormat:@"date >= %@ AND date < %@", beginningOfCurrentMonth, beginningOfNextMonth];
来源:https://stackoverflow.com/questions/13262567/how-to-build-a-nspredicate-filtering-all-days-in-a-month-using-nsdate