我正在使用EventKit.framework来获取存储在EKEventStore
中的事件。
如何才能只获取今天的事件,即从早上 00:00AM 到 11: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/