我试图计算两个日期之间的小时数。当我运行应用程序时,它崩溃了。你能告诉我这段代码中的错误吗?
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);
答案 0 :(得分:12)
参考this answer of a mostly similar question一个更好的,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
。
答案 1 :(得分:11)
我认为差异应该是int值......
NSLog(@"hoursBetweenDates: %d", hoursBetweenDates);
希望,这会对你有帮助..
答案 2 :(得分:3)
使用
无法显示NSIntegerNSLog(@"%@", hoursBetweenDates);
改为使用:
NSLog(@"%d", hoursBetweenDates);
如果不确定使用Apple Developer Docs中的内容: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265