電子趣味の部屋

電子系のガジェットやアプリ開発等の趣味の話題を書いてます

iPhone SDK 本体のローカライズの書式設定に合わせて日付時刻を取得する方法

本体のローカライズの書式設定(言語環境の書式)の設定に合わせて日付時刻を取得する方法

概要

NSDateFormatterのインスタンスメソッドのsetLocaleでロケールを設定。
現在設定されているロケールは[NSLocale currentLocale]で取得できるので、そのままsetLocaleに指定する。
NSDateFormatterのインスタンスメソッドのsetDateStyleで日付の書式、setTimeStyleで時刻の書式を指定したロケールで設定できる。

指定できる定型フォーマット

指定できる定型フォーマットはNSDateFormatterStyleで定義されている5種類
・NSDateFormatterNoStyle
・NSDateFormatterShortStyle
・NSDateFormatterMediumStyle
・NSDateFormatterLongStyle
・NSDateFormatterFullStyle

※ NSDateFormatterNoStyleは何も設定しない(空文字列)です。これは、日付のみ取得して時間は取得したくない時、又はその逆の場合に使用します。

コードサンプル

//現在の日付、時刻を取得
NSDate *now = [[NSDate date] retain];
// NSDateFormatterのインスタンスを取得
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
// 現在のロケールを設定 
[dateFormatter setLocale:[NSLocale currentLocale]];  

// NSDateFormatterNoStyle
[dateFormatter setDateStyle:NSDateFormatterNoStyle];  
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];  
NSString *dateStringNoStyle = [dateFormatter stringFromDate:now];
NSLog(@"NoStyle     : %@", dateStringNoStyle);

// NSDateFormatterShortStyle
[dateFormatter setDateStyle:NSDateFormatterShortStyle];  
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];  
NSString *dateStringShortStyle = [dateFormatter stringFromDate:now];
NSLog(@"ShortStyle  : %@", dateStringShortStyle);

// NSDateFormatterMediumStyle
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];  
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];  
NSString *dateStringMediumStyle = [dateFormatter stringFromDate:now];
NSLog(@"MediumStyle : %@", dateStringMediumStyle);

// NSDateFormatterLongStyle
[dateFormatter setDateStyle:NSDateFormatterLongStyle];  
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];  
NSString *dateStringLongStyle = [dateFormatter stringFromDate:now];
NSLog(@"LongStyle   : %@", dateStringLongStyle);

// NSDateFormatterFullStyle
[dateFormatter setDateStyle:NSDateFormatterFullStyle];  
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];  
NSString *dateStringFullStyle = [dateFormatter stringFromDate:now];
NSLog(@"FullStyle   : %@", dateStringFullStyle);

コードサンプルの実行結果

書式設定が日本語の場合

NoStyle     : 
ShortStyle  : 09/07/16 23:54
MediumStyle : 2009/07/16 23:54:37
LongStyle   : 2009年7月16日 23:54:37JST
FullStyle   : 2009年7月16日木曜日 23時54分37秒JST

書式設定がUnited Statesの場合

NoStyle     : 
ShortStyle  : 7/16/09 11:56 PM
MediumStyle : Jul 16, 2009 11:56:47 PM
LongStyle   : July 16, 2009 11:56:47 PM GMT+09:00
FullStyle   : Thursday, July 16, 2009 11:56:47 PM Japan Time


はじめてのiPhoneプログラミング

はじめてのiPhoneプログラミング