【问题标题】:NSPredicate to get only today's eventsNSPredicate 仅获取今天的事件
【发布时间】:2014-08-01 06:49:55
【问题描述】:

我正在使用 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

【问题讨论】:

  • 这应该可以工作,如果你在午夜运行它。 ;-) 每隔一段时间它就会失败,因为startDate 将是“现在”。将创建 startDate 的代码替换为实际为 creates a NSDate for today midnight 的代码。
  • @MatthiasBauch 我怎样才能得到明天的午夜,即 00AM。如果今天是 7 月 1 日,我怎样才能得到 7 月 2 日的 00AM?
  • 您可以使用NSCalendar方法dateByAddingUnitdateByAddingComponents从开始日期开始。

标签: objective-c ios7 nspredicate eventkit ekeventstore


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    相关资源
    最近更新 更多