如何将NSDate的本地化日期作为字符串?

时间:2012-09-04 08:57:52

标签: iphone ios ipad nsdate nsdateformatter

我有一个NSDate对象,并且必须创建一个标签,用一个简短的3-char样式表示星期几,例如'星期五,'星期二'' Wed',...并以任何语言本地化为简短陈述。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

要使用正确的区域设置,您需要使用+ dateFormatFromTemplate:options:locale:方法在dateFormat的实例上设置NSDateFormatter

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

答案 2 :(得分: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);