Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

[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のカレンダーの設定を、「設定」-> 「一般」->「言語環境」->「カレンダー」から和暦にして、動作確認を一度はした方が良いと思う。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした