web-dev-qa-db-ja.com

2つのNSDate間の時間の違い

ここでは、2つの日付の間の時間を計算しようとしています。アプリケーションを実行すると、クラッシュします。このコードの間違いを教えてください。

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

違いはint値にあるべきだと思います...

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

うまくいけば、これはあなたを助けるでしょう..

11
Nit

ほとんど同様の質問に対するこの回答 より適切で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を使用してください。

12
Hendrik

NSIntegerを使用して表示することはできません

NSLog(@"%@", 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

3
Nic