2011-11-01 64 views
1

當我嘗試計算使用日期組件的時間時,日期爲一秒。爲什麼是這樣?NSDate 1秒關

NSCalendar *sysCalendar = [NSCalendar currentCalendar]; 
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:timeStarted toDate:[[NSDate date]addTimeInterval:+1.0] options:0]; 
timeElapsed = [sysCalendar dateFromComponents:conversionInfo]; 

我臨時的解決辦法是增加一秒,但我想知道爲什麼它正在發生,或者有更好的修復。

編輯:它不是一秒掉,但它是四捨五入。當我以秒爲單位獲得時間間隔(將其降至小數位)時,它會變爲1.9,2.9,3.9,分別顯示爲00:00:01,00:00:02和00:00:03。我怎樣才能把它收集起來?

+1

您可以添加0.5秒。這應該適用於所有情況。但這仍然是一個可怕的解決方案。 – dasdom

回答

1

可以圓一個雙(NSTimeInterval)爲整數搭配:

NSTimeInterval unrounded = 7.8; 
long rounded = lround(unrounded); 

長整型「四捨五入」現在將包含8.您現在可以施放此回的時間間隔。

NSTimeInterval roundedTimeInterval = (NSTimeInterval)rounded; 

並將其與NSDate函數一起使用。

所以,創建具有唯一的全秒一個NSDate可以使用:

NSDate *nowEnough = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)lround([NSDate timeIntervalSinceReferenceDate])]; 

或四捨五入現有的NSDate的亞秒:

NSDate *thenEnough = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)lround([existingNSDatesName timeIntervalSinceReferenceDate])]; 
+0

這將不得不工作。謝謝! – Baub