簡體   English   中英

兩個NSDate之間的小時差異

[英]Difference in hours between two 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);

參考這個大致相似的問題答案,更好和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

我認為差異應該是int值...

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

希望這個能對您有所幫助..

無法使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM