2011-12-09 12 views
7

私は日付ピッカーを持っています。今後NSDatesの配列を取得

これから時間を選択すると、次の月曜日の日付を取得したいと思います。私は、例えばのため

を日付を取り、その日から次の64月曜日ためNSDatesのNSArrayのを返すメソッドを書くことに行くかどう

私は日付ピッカーから時刻を午後6時45分に選んだので、その時刻に設定されている時間とともに次の64時間をフェッチしたいと思います。

+8

は、私は近くの投票に反対します。 –

+0

うん...これは非常に挑戦的な質問です。アヤズ、次の64の月曜日を "フェッチ"したいと言うとき、どのような形でフェッチをしたいですか? NSDatesまたはEKEventsまたは? –

+0

私はNSDatesが欲しい... –

答えて

3

例(ARC):

NSDate *pickerDate = [NSDate date]; 
NSLog(@"pickerDate: %@", pickerDate); 

NSDateComponents *dateComponents; 
NSCalendar *calendar = [NSCalendar currentCalendar]; 

dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate]; 
NSInteger firstMondayOrdinal = 9 - [dateComponents weekday]; 
dateComponents = [[NSDateComponents alloc] init]; 
[dateComponents setDay:firstMondayOrdinal]; 
NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0]; 

dateComponents = [[NSDateComponents alloc] init]; 
[dateComponents setWeek:1]; 

for (int i=0; i<64; i++) { 
    [dateComponents setWeek:i]; 
    NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0]; 
    NSLog(@"week#: %i, mondayDate: %@", i, mondayDate); 
} 

のNSLog出力:
pickerDate:2011-12-09 20:38 :25 0000
週#:0、mondayDate:2011年12月12日20時38分25秒0000
週番号:1、mondayDate:2011年12月19日20時38分25秒0000
週間# :2、monday日付:2011-12-26 20:38:25 +0000
週番号:3、mondayDate:レコードの2012-01-02午後8時38分25秒0000
-the残り60 here-

+0

明確な返信をありがとう。次の4月曜日です。私はそれを4回ではなく63回繰り返すべきですか? –

+0

私はちょうど最初の4つを示し、私はこれをより明確にするために編集しました。 – zaph

+1

ちょうど不思議なことに、 'firstMondayOrdinal'の計算にはどこで' 9 'を得ましたか? –

1

NSCalendarを使用して、今日(選択した時刻に)曜日を指定できます。次の月曜日に到着するまでそれをバンプしてから、それを7日間で63回ぶつけて、あなたが望むような月曜日を得る。

2

ピッカーからNSDateで始まり、月曜日まで24 * 60 * 60秒を追加し続けます。結果の日付を結果に追加します。追加した最後の日付まで7 * 24 * 60 * 60秒を追加し、64の月曜日がすべて終わるまで、結果を戻りリストにプッシュします。ここでNSDateが月曜日にあたるとき、あなたが言う方法です:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest]; 
NSInteger weekday = [weekdayComponents weekday]; 
if (weekday == 2) ... // 2 represents Monday 

EDIT:DaveDeLongは、上記のアルゴリズムの不足を指摘した:それは夏時間ために変更の日に時間を2回シフトします。代わりに、手動で計数秒、NSDateに日を追加するには、このコードを使用する:

NSDate *currentDate = [NSDate date]; 
NSDateComponents *comps = [[NSDateComponents alloc] init]; 
[comps setDay:1]; // Add 1 when searching for the next Monday; add 7 when iterating 63 times 
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0]; 
[comps release]; 
+2

NO NO NO NOこれは夏時間を考慮していません!そして、質問者は、彼が同じ時間を維持したいと明確に言った。 –

+0

@DaveDeLongいいキャッチ!固定具... – dasblinkenlight

+1

@DaveDeLong Appleが過去のパフォーマンスから判断して夏時間を知っているかどうか議論のため多少アップです。 :-) – zaph

関連する問題