26

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);
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
shebi
  • 707
  • 2
  • 14
  • 23
  • 3
    NSLog(@"hoursBetweenDates: %d", hoursBetweenDates); – adali Apr 25 '12 at 07:16
  • 1
    It does not make sense to incorporate changes that solve your problem into the code of the question. After that edit your code wasn't crashing anymore, so I did a rollback to the original version of the question. – Matthias Bauch Apr 25 '12 at 08:32
  • Turn warnings on in your compiler. There is a severe bug, and with warnings turned on, the compiler would have told you about it. – gnasher729 Feb 02 '15 at 10:12
  • Possible duplicate: [How to calculate time in hours between two dates in iOS](https://stackoverflow.com/questions/4084341/how-to-calculate-time-in-hours-between-two-dates-in-ios) – Jon Schneider Oct 29 '20 at 21:55

3 Answers3

12

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.

Community
  • 1
  • 1
Hendrik
  • 940
  • 8
  • 14
11

I think difference should be in int value...

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

Hope, this will help you..

Nitin
  • 7,455
  • 2
  • 32
  • 51
3

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

Nic
  • 2,864
  • 1
  • 16
  • 21