objective-c - NSPredicate 仅获取今天的事件

标签 objective-c ios7 nspredicate eventkit ekeventstore

我正在使用EventKit.framework来获取存储在EKEventStore中的事件。

如何才能只获取今天的事件,即从早上 00:00AM11:59PM(00:00 到 23:59)。时区可以是任何东西。

我正在使用下面的代码,但它也给出了第二天的事件。它正在将今天的日期添加 24 小时。

-(void) fetchEvents{
    NSDate *startDate = [NSDate date] ;

    //Create the end date components
    NSDateComponents *tomorrowDateComponents = [[NSDateComponents alloc] init];
    tomorrowDateComponents.day = 1;

    NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:tomorrowDateComponents
                                                                    toDate:startDate
                                                                   options:0];
    // We will only search the default calendar for our events
    NSArray *calendarArray = [NSArray arrayWithObject:self.defaultCalendar];

    // Create the predicate
    NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate
                                                                      endDate:endDate
                                                             calendars:calendarArray];

    // Fetch all events that match the predicate
    NSMutableArray *events = [NSMutableArray arrayWithArray:[self.eventStore eventsMatchingPredicate:predicate]];
}

如何更改 NSPredicate 以满足上述要求?

最佳答案

如果您想要今天的事件,有很多方法可以做到,但您可以获取当前日期/时间,然后要求日历根据适当的小时、分钟和时间设置开始和结束日期。第二。

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startDate = [calendar dateBySettingHour:0  minute:0  second:0  ofDate:now options:0];
NSDate *endDate   = [calendar dateBySettingHour:23 minute:59 second:59 ofDate:now options:0];

NSPredicate *predicate = [store predicateForEventsWithStartDate:startDate
                                                        endDate:endDate
                                                      calendars:nil];

NSArray *events = [store eventsMatchingPredicate:predicate];

如果您希望 endDate 为第二天的中午 12:00,您可以这样做:

NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];

关于objective-c - NSPredicate 仅获取今天的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25074449/

相关文章:

ios - NSNumber = 0 的谓词

objective-c - 在 XCTest 中完成测试套件运行后执行操作

ios - 从应用程序将文本文件保存在 iOS 目录中

ios - 如何在关闭 UISearchDisplayController 时将文本保留在搜索栏中

ios - 无法在 NSURLSession 委托(delegate)方法中更新用户界面

objective-c - NSPredicate检索其1:n关系中的属性不是NIL的所有对象

objective-c - 使用具有一对多关系的 NSPredicate 获取父对象

ios - 如何在类别中创建 UITableViewCell 明智地排列 JSON 对象

ios - 在 iOS 框架中将符号标记为未定义

iphone - 应用程序发布后,对如何更新 UITableView 上的数据源感到困惑