2013年8月21日水曜日

年の差を求める

2つのNSDate間の年の差を求める。例えば誕生日から現在までの年数を求めるような場合、うるう年を考慮する必要があるので、NSCalendar、NSDateComponentsを使用すると便利。

// NSDate *birthDate から現在までの年の差を求める(年齢を求める)
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diffComponents
= [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
              fromDate:birthDate
                toDate:[NSDate date]
               options:0];
NSInteger year = [diffComponents year];
NSLog(@"year:%d", year);

0 件のコメント:

コメントを投稿