shebi
shebi

Reputation: 719

Difference in hours between two NSDate

Here I'm trying to calculate the hours between two dates. When i run the application, it crashes. Could you please tell me the mistake in this code?

NSString *lastViewedString = @"2012-04-25 06:13:21 +0000";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];

NSDate *lastViewed = [[dateFormatter dateFromString:lastViewedString] retain];
NSDate *now = [NSDate date];

NSLog(@"lastViewed: %@", lastViewed); //2012-04-25 06:13:21 +0000
NSLog(@"now: %@", now); //2012-04-25 07:00:30 +0000

NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:lastViewed];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

NSLog(@"hoursBetweenDates: %@", hoursBetweenDates);

Upvotes: 26

Views: 12238

Answers (3)

Hendrik
Hendrik

Reputation: 940

Referring to this answer of a mostly similar question a better and Apple approved way would be using the NSCalendar methods like this:

- (NSInteger)hoursBetween:(NSDate *)firstDate and:(NSDate *)secondDate {
   NSUInteger unitFlags = NSCalendarUnitHour;
   NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   NSDateComponents *components = [calendar components:unitFlags fromDate:firstDate toDate:secondDate options:0];
   return [components hour]+1;
}

If you target iOS 8 or later use NSCalendarIdentifierGregorian instead of the deprecated NSGregorianCalendar.

Upvotes: 12

Nic
Nic

Reputation: 2864

NSInteger can't be shown by using

NSLog(@"%@", hoursBetweenDates);

instead use:

NSLog(@"%d", hoursBetweenDates); 

If unsure what to use look in the Apple Developer Docs: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265

Upvotes: 3

Nitin
Nitin

Reputation: 7461

I think difference should be in int value...

NSLog(@"hoursBetweenDates: %d", hoursBetweenDates);

Hope, this will help you..

Upvotes: 11

Related Questions