Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 819
shebi Avatar asked Sep 10 '25 19:09

shebi


1 Answers

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.

like image 109
Hendrik Avatar answered Sep 12 '25 20:09

Hendrik