NSDateを変更して今日から1か月を表す
-
06-07-2019 - |
質問
作業中のCocoaアプリに繰り返しイベントを追加しています。これらを数学的に定義できるため(3600 * 24 * 7 = 1週間)、毎日および毎週正常に繰り返しています。次のコードを使用して日付を変更します。
[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]
イベントが繰り返されてから何ヶ月が経過したかは知っていますが、1ヵ月/ 3ヵ月/ 6ヵ月/ 9ヵ月先を表すNSDateオブジェクトを作成する方法がわかりません。理想的には、ユーザーに10月14日から毎月繰り返し、そして毎月14日を繰り返すように言ってほしい。
解決
(この質問とほぼ同じ。)
ドキュメントから:
NSCalendarDateの強力な使用 がっかり。まだ非推奨ではありませんが、 ただし、次の主要なOSにある可能性があります Mac OS X v10.5以降のリリース。にとって カレンダー計算、あなたがする必要があります 適切な組み合わせを使用する NSCalendar、NSDate、および NSDateComponents、で説明されている 日付と時刻のカレンダー Cocoaのプログラミングトピック。
そのアドバイスに従う:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];
NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];
nextMonthComponents.day = todayDayComponents.day;
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];
[gregorian release];
より直接的または効率的な実装がありますが、これは正確であり、正しい方向を向いている必要があります。
他のヒント
NSCalender、NSDateComponentsおよびNSDateを使用:
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
components.month = 1;
NSDate *oneMonthFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];
components
の異なるプロパティを設定して、異なる期間(3か月、6か月など)を取得します。
注:コンテキストによっては、 [NSCalendar currentCalendar]
ではなく、 [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]
を使用することもできます。 「1か月」 「グレゴリオ暦の1か月」という意味です。
おそらくNSCalendarDateを使用します。
現在の日付のdayOfMonth、monthOfYear、yearOfCommonEraを3つの数値として取得します。
必要な月数(1/3/6/9)を追加し、1)その日付が存在するかどうか(例:4月31日、非うるう年の2月29日)、および2)のロールオーバー年。
NSCalendarDateのinitWithYear:month:day:hour:minute:second:timeZone:
で新しい日付を作成しますNSCalendarDate は新しいSDKでサポートされなくなりました。配布用にビルドする際に問題が発生します。
次のようにできます:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:nextMonth];
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];
[gregorian release];