如何检查NSDate是否介于两次之间?

时间:2012-08-24 16:34:58

标签: cocoa nsdate

我正在制作一个Cocoa应用程序,我希望它能够进行每日更新。 (这个应用程序是供个人使用的)我希望它在每天的特定时间进行更新,所以我将计算机设置为在那个时候醒来。我在我的应用程序中设置了一个通知观察者的东西,如果应用程序让计算机发出清醒通知,它将执行此功能:

- (void) receiveWakeNote: (NSNotification*) note
{
   [self conductBeginning];
}

我应该添加什么来确保唤醒通知发生在特定时间(例如16:00到16:15)之间,然后才执行

[self conductBeginning];

线。

2 个答案:

答案 0 :(得分:2)

NSDate *now = [NSDate date];

NSUInteger units = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
                                                               fromDate:now];
if (components.hour == 16 && components.minute <= 15)
    NSLog(@"it's time");

答案 1 :(得分:0)

类似的东西:

NSDate * aDate = ...;
NSDate * bDate = ...;

NSTimeInterval a = [aDate timeIntervalSinceNow];
NSTimeInterval b = [bDate timeIntervalSinceNow];
NSTimeInterval min = a > b ? b : a;
NSTimeInterval max = a < b ? b : a;
NSTimeInterval now = CFAbsoluteTimeGetCurrent();

bool result = now >= min && now <= max;