xcode 两个 NSDate 之间的小时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10310997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference in hours between two NSDate
提问by shebi
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);
采纳答案by Nitin
I think difference should be in int value...
我认为差异应该在 int 值上...
NSLog(@"hoursBetweenDates: %d", hoursBetweenDates);
Hope, this will help you..
希望能帮到你..
回答by Hendrik
Referring to this answer of a mostly similar questiona better and Apple approved way would be using the NSCalendar methods like this:
参考this answer of amost 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;
}
If you target iOS 8 or later use NSCalendarIdentifierGregorian
instead of the deprecated NSGregorianCalendar
.
如果您的目标是 iOS 8 或更高版本,请使用NSCalendarIdentifierGregorian
已弃用的NSGregorianCalendar
.
回答by Nic
NSInteger can't be shown by using
NSInteger 不能通过使用显示
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
如果不确定要使用什么,请查看 Apple Developer Docs:http: //developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265