LoginSignup
44
44

More than 5 years have passed since last update.

[iOS] [Objective-C] currentCalendar を使ってはいけない

Last updated at Posted at 2014-07-25

[NSCalendar currentCalendar] を使ってはいけない

使うと、iOSのカレンダー設定が和暦のときにpickerやdatefommaterの年に関連する数値が全部和暦で計算されて、年齢が2000歳になる、みたいなバグが発生する。
例えば、誕生日の表示が63年2月3日とかになる。

代わりに、下記のようにする。

[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

同様に下記の2点も気をつける

  • UIDatePickerを使うときは calendar を設定する
picker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.locale = [NSLocale currentLocale];
picker.calendar = gregorian;

 
* NSDateFormatterを使うときも calendar を設定する

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

上記の設定をすると年の表記や、数値としての取り扱い方を西暦で統一できる。
日付を扱っているアプリの場合、iOSのカレンダーの設定を、「設定」-> 「一般」->「言語環境」->「カレンダー」から和暦にして、動作確認を一度はした方が良いと思う。

44
44
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
44
44