how to build a NSPredicate filtering all days in a month using NSDate?

随声附和 提交于 2020-01-04 02:02:15

问题


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 NSDates, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!