2011-11-24 110 views
18

我使用dateformatter在我的應用程序中獲取日期和時間。 但我面臨一個問題,當我改變手機的語言dateformatter返回我的手機所選語言的日期和時間,由於我的應用程序崩潰,因爲我們不支持多種語言。 任何人都可以請幫我在這裏。Nsdateformatter返回我選擇的手機語言的一天。它可以一直返回我只有英語嗎?

請找到下面的代碼片段:

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); 

當我選擇手機語言爲Gujrati(印度),我現在用使用這是如下的NSLog看到輸出,

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]; 

在你的情況,

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

同樣,對於所有dateformatters。

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) 
相關問題