2011-10-05 22 views
38

NSDateを月日から作成しようとしています(すべて整数形式)。日、月、年からNSDateを生成

今の私の試みは、このような:2011

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、年=:

0168-07-25 04:56:02 +0000

私は何かひどく間違ったことをしているに違いないが、私は何も考えていない。誰でも何が起こっているのか知っていますか?あなたは、年二回の値で2回目をsetMonthを呼び出している

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

は、2016年の終わりにここに来て、この質問にはまだ便利です。これに30の有益な投票があることを考えれば、可能ならば私は再び投票するだろう。さらに、クローズ有権者の中には、トップタグに客観的なc、iOS、cocoa-touch、cocoa、nsdateというプロファイルがあります。 – matrixugly

答えて

38

あなたはあなたのコードのタイプミスを持っています。次のようになります。グリッチを睨ん

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

しかし、あなたがそれを分けたときにALMOSTが動いています。なぜ年が168か167か、なぜ日が25か24かはわかりません。しかし、貧弱なNSDateComponentsオブジェクトは間違いなく混乱していました。 –

+0

(timeZoneをGMTに設定することができないため、日が切れている可能性があります) –

+3

ありがとう!間違いなく目の別のセット(またはコーヒーの別のポット)が必要です:) – minimalpop

2

setYear:あるべき最後の行):

2

一つは次のとおりです。

[components setMonth:[year intValue]]; //setting month with year! 
関連する問題