LoginSignup
3
4

More than 5 years have passed since last update.

NSDateFormatterで年月だけ表示したい

Last updated at Posted at 2015-09-25

欲しいもの

Language Calendar output
日本語 和暦 平成27年9月
西暦 2015年9月
English Japanese September 27 Heisei
Gregorian September 2015

英語表記は、カンマの有無とかよく分からないので、大体こんな感じということで。
当然、英語だけではなく他の言語でもそれなりの表記にならないといけない。

NSDateIntervalFormatterStyle

まずはスタイル指定による表示を調査。

NSDateFormatter *df = [NSDateFormatter new];
df.dateStyle = NSDateIntervalFormatterFullStyle;
NSLog(@"dateFormat=%@", df.dateFormat);
NSLog(@"output=%@", [df stringFromDate:[NSDate date]]);

こんな感じで、Language/Calendar/Styleを変えつつ調査。

Language Calendar Style dataFormat output
日本語 和暦 Full Gy年M月d日EEEE 平成27年9月25日金曜日
Long Gy年M月d日 平成27年9月25日
Medium GGGGGyy/MM/dd H27/09/25
Short GGGGGyy/MM/dd H27/09/25
日本語 西暦 Full y年M月d日EEEE 2015年9月25日金曜日
Long y年M月d日 2015年9月25日
Medium y/MM/dd 2015/09/25
Short y/MM/dd 2015/09/25
English Japanese Full EEEE, MMMM d, y G Friday, September 25, 27 Heisei
Long MMMM d, y G September 25, 27 Heisei
Medium MMM d, y G Sep 25, 27 Heisei
Short M/d/y GGGGG 9/25/27 H
English Gregorian Full EEEE, MMMM d, y Friday, September 25, 2015
Long MMMM d, y September 25, 2015
Medium MMM d, y Sep 25, 2015
Short M/d/yy 9/25/15

当然のことながら「日」まで表示されるので使えない。
Longの「日」が無ければOKな感じ。

dateFormatFromTemplate:options:locale:

ざっくりとした書式からイイ感じの書式を生成してくれるメソッド(たぶん)。

NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yM"
                                                options:0
                                                 locale:[NSLocale currentLocale]];
NSLog(@"dateFormat=%@", df.dateFormat);
NSLog(@"output=%@", [df stringFromDate:[NSDate date]]);

こんな感じで、Language/Calendarを変えつつ調査。

Language Calendar dataFormat output
日本語 和暦 GGGGGy/M H27/9
西暦 y/M 2015/9
English Japanese M/y GGGGG 9/27 H
Gregorian M/y 9/2015

なんかいけそうな気がしてきたので書式をいじってみた結果‥

書式
@"yMMMM"
Language Calendar dataFormat output
日本語 和暦 Gy年M月 平成27年9月
西暦 y年M月 2015年9月
English Japanese MMMM y G September 27 Heisei
Gregorian MMMM y September 2015
ภาษาไทย ญี่ปุ่น MMMM G y กันยายน เฮเซ 27
คริสต์ศักราช MMMM G y กันยายน ค.ศ. 2015

パーフェクト!
めでたいのでタイ語のオマケ付!

しかし、Mを増やすと年に影響が出る(「平成」とか「年」とか表示される)のが気持ち悪い。

まとめ

NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yMMMM"
                                                options:0
                                                 locale:[NSLocale currentLocale]];
NSLog(@"output=%@", [df stringFromDate:[NSDate date]]);
3
4
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
3
4