Vedaant Arora
Vedaant Arora

Reputation: 217

How can I check that NSDate is between two times?

I am making a Cocoa application and I want it to be able to conduct a daily update. (this app is for personal use) I want it to be doing its update at a specific time everyday so I set my computer to wake up at a that time. I set a notification observer thing in my app and it will conduct this function if the app gets a computer did awake notification:

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

What should I add to make sure that the wake up notice occurred between a specific time, say between 16:00 and 16:15, and then only execute the

[self conductBeginning];

line.

Upvotes: 0

Views: 365

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81878

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");

Upvotes: 2

justin
justin

Reputation: 104728

something like this:

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;

Upvotes: 0

Related Questions