Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 261
Raphael Caixeta Avatar asked Aug 03 '10 19:08

Raphael Caixeta


2 Answers

NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
    // hooray!
like image 198
Noah Witherspoon Avatar answered Oct 15 '22 04:10

Noah Witherspoon


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];
like image 28
E. Criss Avatar answered Oct 15 '22 02:10

E. Criss