How to calculate the number of hours with NSDate

I started NSDate with [NSDate date]; and I want to check if it was 5 hours with this NSDate variable. How should I do it? What do I have in my code

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

In a later method, I want to check if it has been 12 hours since the request. Please help! Thanks in advance.

+5
source share
3 answers
int seconds = -(int)[requestTime timeIntervalSinceNow];
int hours = seconds/3600;

Mostly here I ask how many seconds have passed since we received our request. Then with a little mathematical magic, which is divided by the number of seconds per hour, we can get the number of hours passed.

. , "" . xcode , NSDate .

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

Try using this method or something in that direction.

- (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;
}

Then you can do a simple check of the integer hourly response.

int hours = [dateUtilityClass hoursSinceDate:dateInQuestion];
if(hours < 5){
    # It has not yet been 5 hours.
}
0
source

All Articles