ここでは、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);
違いはint値にあるべきだと思います...
NSLog(@"hoursBetweenDates: %d", hoursBetweenDates);
うまくいけば、これはあなたを助けるでしょう..
ほとんど同様の質問に対するこの回答 より適切で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
を使用してください。
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