如何使用 NSDate 构建一个 NSPredicate 过滤一个月中的所有天数? [英] how to build a NSPredicate filtering all days in a month using NSDate?

查看:51
本文介绍了如何使用 NSDate 构建一个 NSPredicate 过滤一个月中的所有天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法一般地获得一个月中的所有天数?

Is there a way to get all days in a month generically ?

像这样:

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

推荐答案

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

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

一旦你得到了这两个 NSDate ,那么你就可以:

Once you've got those two NSDates, then you can do:

[NSPredicate predicateWithFormat:@"date >= %@ AND date < %@", beginningOfCurrentMonth, beginningOfNextMonth];

这篇关于如何使用 NSDate 构建一个 NSPredicate 过滤一个月中的所有天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆