LoginSignup
5
5

More than 5 years have passed since last update.

NSCalendarとNSDateを使って年齢を取得する

Last updated at Posted at 2014-02-01

NSCalendarとNSDateを使って年齢を取得するコード。

なんでこんなことを書いているかというと、
例えば、和暦を使っている人の環境でいま year を取得すると、結果は平成n年の値が返って来る。
なので昭和59年生まれの人が平成26年に何歳になったか確認したいときに、

yearsOld = nowYear - birthdayYear;

みたいな計算をしてしまうと、

yearsOld = -33;//= (平成)26 - (昭和)59

という残念な結果になる。

これが年齢を取得するコード。

NSCalendar *calendar = self.calendar;
NSDate     *nowDate  = [NSDate date];
NSInteger   year     = [[calendar components:NSYearCalendarUnit
                                            fromDate:birthday
                                              toDate:nowDate
                                             options:0] year];
printf("%ld years old\n", year);

和暦で確認したければ

self.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSJapaneseCalendar];

西暦(グレゴリオ暦)で確認したければ

self.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

などと先にやっておいてください。 (この2つのカレンダーでは結果はいっしょです。)
このしたに書いてあるのは、誕生日のサンプルです。

NSDateComponents *birthdayComponents = [[NSDateComponents alloc] init];
[birthdayComponents setYear:1984];
[birthdayComponents setMonth:1];
[birthdayComponents setDay:24];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate     *birthday          = [gregorianCalendar dateFromComponents:birthdayComponents];
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5