Difference in hours between two NSDate
12,158
Solution 1
I think difference should be in int value...
NSLog(@"hoursBetweenDates: %d", hoursBetweenDates);
Hope, this will help you..
Solution 2
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
.
Solution 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
Related videos on Youtube
Author by
shebi
Updated on June 13, 2022Comments
-
shebi almost 2 years
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);
-
adali about 12 yearsNSLog(@"hoursBetweenDates: %d", hoursBetweenDates);
-
Matthias Bauch about 12 yearsIt 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.
-
gnasher729 about 9 yearsTurn warnings on in your compiler. There is a severe bug, and with warnings turned on, the compiler would have told you about it.
-
deniz over 3 yearsPossible duplicate: How to calculate time in hours between two dates in iOS
-