views:

63

answers:

2

I initiated an NSDate with [NSDate date]; and I want to check whether or not it's been 5 hours since that NSDate variable. How would I go about doing that? What I have in my code is

requestTime = [[NSDate alloc] init];
requestTime = [NSDate date];

In a later method I want to check whether or not it's been 12 hours since requestTime. Please help! Thanks in advance.

+2  A: 
int seconds = -(int)[requestTime timeIntervalSinceNow];
int hours = seconds/3600;

Basically here I'm asking how many seconds have passed since we first got our requestTime. Then with a little math magic, aka dividing by the number of seconds in an hour, we can get the number of hours that have passed.

A word of caution. Make sure you use the "retain" keyword when setting the requesttime. xcode likes to forget what NSDate objects are set to without it.

    requestTime = [[NSDate date] retain];
E. Criss
+1  A: 
NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
    // hooray!
Noah Witherspoon