两个 NSDate 之间的小时差异



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

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

参考这个几乎相似的问题的答案,一个更好的和苹果认可的方法是使用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

我认为差异应该在于整数值...

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

希望,这会对你有所帮助。

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

最新更新