2013-10-30 53 views
1

我是新來的ios編程。使用initWithTimeInterval遇到問題

我想通過下面的代碼得到死亡日期。 但是,我得到了意想不到的結果。

在下面的示例代碼,一個人的出生日期是1899年12月31日和這個人的死亡年齡爲80

所以,我希望這個人的deathdate是1979年12月31日。 但是,我得到的結果是1843-11-05 08:31:44 +0000。

任何人都可以告訴我這段代碼有什麼問題嗎?

謝謝!

NSInteger year = [_selectedDeathAge intValue]; 
NSLog(@"%d", year); //80 

NSLog(@"%@", _selectedBirthDate);//(NSDate)1899-12-31 15:00:00 +0000 

NSDate *deathDate = [_selectedBirthDate initWithTimeInterval:year * 365 * 24 * 60 * 60 sinceDate:_selectedBirthDate]; 

NSLog(@"%@", deathDate);//(NSDate)1843-11-05 08:31:44 +0000 

回答

2

不要用NSDate做相對日期的計算。使用NSCalendarNSDateComponents

NSCalendar *cal = [NSCalendar currentCalendar]; 
NSDateComponents *yearsComponents = [[NSDateComponents alloc] init]; 
yearsComponents.year = [_selectedDeathAge intValue]; 
NSDate *deathDate = [cal dateByAddingComponents:yearsComponents toDate:_selectedBirthDate]; 
+0

非常感謝!有用!!我在4分鐘內接受你的回答。 – crzyonez777

1

NSDate *deathDate = [_selectedBirthDate initWithTimeInterval:year * 365 * 24 * 60 * 60 sinceDate:_selectedBirthDate];

此行是錯誤的,你應該期望奇怪的結果。你正在初始化一個已經初始化的函數。你需要通過[[NSDate alloc] initWithTimeInterval:sinceDate:]創建它,此外,你不應該像這樣硬編碼時間間隔。看起來NSDateComponents

+0

謝謝你的迴應。我要查找NSDateComponents。 – crzyonez777

2

您不應該在另一個實例上調用initWithTimeInterval:sinceDate:方法。

你應該不是這樣:

NSDate *deathDate = [_selectedBirthDate dateByAddingTimeInterval:year * 365 * 24 * 60 * 60]; 

或者你也可以這樣來做:

NSDate *deathDate = [[NSDate alloc] initWithWithTimeInterval:year * 365 * 24 * 60 * 60 sinceDate:_selectedBirthDate]; 

但最終,你應該從「雅各Relkin」使用該解決方案。這是這種計算方法的更好解決方案。

+0

感謝您的幫助。哦,那是真的。 _selectedBirthDate是一個初始化對象。我不應該在這裏調用initilize方法。我投了你的答案!非常感謝你!!! – crzyonez777