Raphael Caixeta
Raphael Caixeta

Reputation: 7846

How to tell amount of hours since NSDate

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.

Upvotes: 5

Views: 4826

Answers (3)

preynolds
preynolds

Reputation: 790

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.
}

Upvotes: 1

E. Criss
E. Criss

Reputation: 342

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

Upvotes: 14

Noah Witherspoon
Noah Witherspoon

Reputation: 57149

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

Upvotes: 15

Related Questions