Difference in hours between two NSDate Difference in hours between two NSDate ios ios

Difference in hours between two NSDate


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.


I think difference should be in int value...

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

Hope, this will help you..


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


matomo