2012-09-04 33 views
1

我有一個NSDate對象,並且必須創建一個標籤,用於指示星期幾,如'星期一','星期二','星期三'等簡短的3字符風格,並且本地化爲任何短代表語言。如何獲得作爲字符串的NSDate的本地化日期?

日期格式化程序EEE有3個字符,但是如何轉換爲可能只有一個字符的中文等語言?

+0

是,'NSDateFormatter'它。您需要格式化程序對象的'setDateFormat:'。使用此鏈接獲取unicode日期格式模式。 http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns – Desdenova

+0

聖經是** [NSDateFormatter類參考](https://developer.apple.com/library/mac/ #documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html)**,_Managing Weekday Symbols_部分。 – holex

+0

感謝downvote。我不明白管理平日符號部分。它讓我設置週日符號。所以呢? –

回答

7
NSDate *date = [NSDate date]; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"EEE"]; 
NSString *strDate = [formatter stringFromDate:date]; 
[formatter release]; 
//Commented out the following line as weekday can be of one letter (requirement changed) 
//strDate = [strDate substringToIndex:3]; //This way Monday = Mon, Tuesday = Tue 
1

這將打印你所需要的:

NSDate *date = [NSDate date]; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"EEEE"]; 
NSString *day = [formatter stringFromDate:date]; 
[formatter release]; 
if ([day length] > 3) day = [day substringToIndex:3]; 
NSLog(@"%@", day); 
+0

「EEE」是否適用於所有地區? –

+0

@ProudMember更新了我的答案。如果一天的字符串更長,然後3個字符,然後它被裁剪。 GL – Nekto

+0

夥計們請停止戰鬥。我的問題還沒有完全解答。我詢問了本地化方面,但沒有得到答案。 –

4

要使用正確的語言環境,你會想用+ dateFormatFromTemplate:options:locale:方法來設置的NSDateFormatter實例的dateFormat

NSDate *date = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEE" options:0 locale:[NSLocale currentLocale]]; 
NSLog(@"Weekday using %@: %@", [[NSLocale currentLocale] localeIdentifier], [dateFormatter stringFromDate:date]); 

// Test what Chinese will look like without changing device locale in settings 
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]; 
NSLog(@"Weekday using zh_CN: %@", [dateFormatter stringFromDate:date]); 

此打印:

平日使用EN_US:週四
平日使用zh_CN的:週四

相關問題