LoginSignup
8
7

More than 5 years have passed since last update.

iOS6のNSDateFormatterの罠

Last updated at Posted at 2013-11-22

日付文字列から日付型に変換する処理をiOSで書く場合はNSDateFormatterを使用するのが基本だと思うがiOSのバージョンのよって挙動が違うので要注意。

例えば「9999-12-31 23:59:59」を無期限を表す日付としてこれを変換する場合

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"];

NSString *dateString = @"9999-12-31 23:59:59";
NSDate *date = [dateFormatter dateFromString:dateString];

NSLog(@"%@", [dateFormatter stringFromDate:date]);   // => 9999-12-31 23:59:59

となるがiOS6の場合は「1999-12-31 23:59:59」と誤変換されてしまう。
iOS7の場合は正常に変換出来る。

※確認したところiOS6の場合は「3513-12-31 23:59:59」を超えると正常に変換できなかった。

これを正常に変換するためにはNSCalendarとNSDateComponentsを使用する。

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.year = 9999;
dateComponents.month = 12;
dateComponents.day = 31;
dateComponents.hour = 23;
dateComponents.minute = 59;
dateComponents.second = 59;

NSDate *date = [calendar dateFromComponents:dateComponents];
NSLog(@"%@", [dateFormatter stringFromDate:date]);   // => 9999-12-31 23:59:59

としてやると正常に変換出来る。

※NSDateFormatterのロケールは必ず指定しないと和暦表示になっていたりする場合、変換後がおかしくなるので注意。

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