Objective-Cでの日付の計算

NSDate, NSCalendar, NSDateComponentsを使えば日付の計算、例えば1年後の本日などは簡単に求めることができます。

例) 1年後の日付

```NSDate *today = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setYear:1];
NSDate *date = [cal dateByAddingComponents:comps toDate:today options:0];

<pre><code><br />例) 10日前の日付

```NSDate *today = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:-10];
NSDate *date = [cal dateByAddingComponents:comps toDate:today options:0];

例) 1週間後の日付

NSDate *today = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setWeek:1];
NSDate *date = [cal dateByAddingComponents:comps toDate:today options:0];

この記事が役に立った場合、シェアしていただけると励みになります!!