2011-10-05 41 views
38

我試圖從一個月和一年中生成一個NSDate(全部爲整數格式)。從日,月和年生成NSDate

現在我的嘗試是這樣的:

NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *components = [[NSDateComponents alloc] init]; 
NSNumber *day = [dataSource valueForKey:@"day"]; 
NSNumber *month = [dataSource valueForKey:@"month"]; 
NSNumber *year = [dataSource valueForKey:@"year"]; 
[components setDay:[day intValue]]; 
[components setMonth:[month intValue]]; 
[components setMonth:[year intValue]]; 
NSDate *_date = [calendar dateFromComponents:components]; 

然而,_DATE輸出以下時天= 24個月= 8年= 2011:

0168-07-25 4時56分02秒+0000

我必須做一些可怕的錯誤,但我不知道是什麼。任何人都知道可能會發生什麼?

+0

來到這裏,在2016年底,這問題仍然是有幫助的。鑑於有30個有用的投票,我會投票重新打開,如果可能的話。此外,沒有任何一位精選的選民在他們的頂級標籤中查看他們的個人資料時,有objective-c,iOS,cocoa-touch,cocoa,nsdate。 – matrixugly

回答

38

你在你的代碼一個錯字:(最後一行應setYear:

[components setDay:[day intValue]]; 
[components setMonth:[month intValue]]; 
[components setYear:[year intValue]]; 
+0

是的,當你把它分開的時候,它幾乎可以解決 - 不清楚爲什麼年份是168比167,或者爲什麼一天25比24。但是可憐的NSDateComponents對象無疑是非常混亂的。 –

+0

(由於無法將時區設置爲GMT,因此當天可能會關閉。) –

+3

謝謝!肯定需要另一套眼睛(或另一壺咖啡):) – minimalpop

2

要調用setMonth兩次,第二次與一年的價值。應該是:

[components setDay:[day intValue]]; 
[components setMonth:[month intValue]]; 
[components setYear:[year intValue]]; 
2

一個明顯的毛刺是:

[components setMonth:[year intValue]]; //setting month with year!