Question

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.

Was it helpful?

Solution

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

OTHER TIPS

NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
    // hooray!

Try using this method, or something along these lines.

- (int)hoursSinceDate :(NSDate *)date
{
    #define NUBMER_OF_SECONDS_IN_ONE_HOUR 3600

    NSDate *currentTime = [NSDate date];
    double secondsSinceDate = [currentTime timeIntervalSinceDate:date];
    return (int)secondsSinceDate / NUBMER_OF_SECONDS_IN_ONE_HOUR;
}

You can then do a simple check on the integer hour response.

int hours = [dateUtilityClass hoursSinceDate:dateInQuestion];
if(hours < 5){
    # It has not yet been 5 hours.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top