NSPredicate只获得今天的活动

时间:2014-08-01 06:49:55

标签: objective-c ios7 nspredicate eventkit ekeventstore

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

我怎样才能获得今天的活动,例如从早上 00:00 晚上11:59 (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

1 个答案:

答案 0 :(得分:4)

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

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在第二天凌晨00:00,您可以执行以下操作:

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