26

在这里,我试图计算两个日期之间的小时数。当我运行应用程序时,它崩溃了。你能告诉我这段代码中的错误吗?

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);
4

3 回答 3

12

参考这个几乎类似的问题的答案,一个更好的、Apple 认可的方法是使用这样的 NSCalendar 方法:

- (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;
}

如果您以 iOS 8 或更高版本为目标NSCalendarIdentifierGregorian,请使用已弃用的NSGregorianCalendar.

于 2014-02-05T14:53:04.857 回答
11

我认为差异应该是 int 值......

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

希望对你有帮助..

于 2012-04-25T07:18:56.863 回答
3

NSInteger 不能通过使用显示

NSLog(@"%@", hoursBetweenDates);

改为使用:

NSLog(@"%d", hoursBetweenDates); 

如果不确定要使用什么,请查看 Apple 开发人员文档:http: //developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265

于 2012-04-25T07:20:38.937 回答