2014-05-14 105 views
0

比較兩個日期(currentDate_timerStartDate)後,我得到以下輸出獲得意想不到的輸出NSDateComponents

nstimeinterval: 88.998212 
2014-05-14 14:07:08.284 currentDate: 14-05-2014 14:07:08 
2014-05-14 14:07:08.284 stopDate: 14-05-2014 14:05:39 
2014-05-14 14:07:08.284 hour: 10 

這是正確的和預期。然而,當我打破timerDate下來,我從NSLog得到10個小時......我期待着零。我究竟做錯了什麼?

這裏是我的代碼:

NSDate *currentDate = [NSDate date]; 
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:_timerStartDate]; 
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"mm:ss"]; 
NSString *timeString=[dateFormatter stringFromDate:timerDate]; 


NSLog(@"nstimeinterval: %f", timeInterval); 

[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"]; 

NSLog(@"currentDate: %@", [dateFormatter stringFromDate:currentDate]); 
NSLog(@"stopDate: %@", [dateFormatter stringFromDate:_timerStartDate]); 


NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *components = [calendar components: (NSHourCalendarUnit | NSYearCalendarUnit) fromDate:timerDate]; 
NSLog(@"year: %li", (long)components.year); 


NSLog(@"timer: %@", timeString); 

timerTicksForCounter = timeString; 

NSLog(@"hour: %li", (long)components.hour); 
+1

您似乎對這些API中某些API的意圖感到困惑。如果你想要量化兩個日期之間的差異,你可以使用'components:fromDate:toDate:options:'method,a la:[[calendar components:NSCalendarUnitHour fromDate:_timerStartDate toDate:currentDate options:0];' – warrenm

回答

0

它是什麼,你實際上要完成?用兩天之間的時間填充NSDateComponents?在這種情況下,您可能需要-[NSCalendar components:fromDate:toDate:options:],其中從開始日期開始,到目前爲止,您停止當前日期。與此同時,你似乎在做很多複雜的事情,並且可能不需要把日期混合在一起。