2

我有一个 NSDate 对象,并且必须创建一个标签,以短的 3 字符样式指示一周中的哪一天,例如“Mon”、“Tue”、“Wed”……并本地化为任何语言的短表示。

日期格式化程序 EEE 有 3 个字符,但它如何翻译成像中文这样可能只有一个字符的语言?

4

3 回答 3

8
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
于 2012-09-04T09:08:40.690 回答
4

要使用正确的语言环境,您需要在使用该方法dateFormat的实例上设置 。NSDateFormatter+ dateFormatFromTemplate:options:locale:

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 :周四

于 2012-09-06T21:59:06.057 回答
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);
于 2012-09-04T09:03:08.353 回答