2011-11-24 17 views
18

私は自分のアプリケーションで日時を取得するために、dateformatterを使用しています。 しかし、私は電話のdateformatterの言語を変更するときに、私は複数の言語をサポートしていない私のアプリケーションがクラッシュするため、電話の選択された言語の日と時間を返します問題に直面している。 誰もこの中で私を助けてくれますか?Nsdateformatterは選択された電話の言語で私の日を返します。私は英語だけを常に返すことができますか?

以下のコードスニペットを見つけてください、私はGujrati(インド)などの電話言語を選択すると、以下のように私はこれを使用してのNSLogを使用して見ていた出力がある

NSDate *date=[NSDate date]; 
NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init]; 
[objTimeFotmatter setDateFormat:@"HH:mm"]; 

NSDateFormatter *objDayFotmatter=[[NSDateFormatter alloc]init]; 
[objDayFotmatter setDateFormat:@"EEEE"]; 

NSString *objTime=[objTimeFotmatter stringFromDate:date]; 
NSString *objDay=[objDayFotmatter stringFromDate:date]; 

NSLog(@"objTime=%@",objTime); 
NSLog(@"objDay=%@",objDay); 

2011-11-24 11:23:20.221 Belkin_Plugin[1110:707] objTime=૧૧:૨૩ 
2011-11-24 11:23:20.227 Belkin_Plugin[1110:707] objDay=ગુરુવાર 
+0

これは、[この一つとして]同じ質問(http://stackoverflow.com/questions/1348590/how-to-make-nsdateformatter-display-locale-specificかもしれません-date)??? –

+0

@breakfreehg:私の答えを見てください。それは私のために働き、あなたのために働くでしょう。 :] –

答えて

45

次の行をdateformatterに追加します。あなたのケースでは

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[dateFormatter setLocale:usLocale]; 

、すべてのdateformattersについて同様

NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init]; 
[objTimeFotmatter setDateFormat:@"HH:mm"]; 
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[objTimeFotmatter setLocale:usLocale]; 

1

は、このコードを試してみてください。

NSDate *date=[NSDate date]; 
NSDateFormatter *objTimeFotmatter=[[NSDateFormatter alloc]init]; 
[objTimeFotmatter setDateFormat:@"HH:mm"]; 
[objTimeFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] 
autorelease]]; 
NSDateFormatter *objDayFotmatter=[[NSDateFormatter alloc]init]; 
[objDayFotmatter setDateFormat:@"EEEE"]; 
[objDayFotmatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] 
autorelease]]; 
NSString *objTime=[objTimeFotmatter stringFromDate:date]; 
NSString *objDay=[objDayFotmatter stringFromDate:date]; 
[objDayFotmatter release]; 
[objTimeFormatter release]; 

NSLog(@"objTime=%@",objTime); 
NSLog(@"objDay=%@",objDay); 

ホープこれはあなたを助けます。

1

スウィフト

let dateFormatter = DateFormatter() 
dateFormatter.locale = NSLocale(localeIdentifier: "en_US") as Locale! 
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" 
let resultsDate = dateFormatter.string(from: date) 
関連する問題