2013-09-23 211 views
3

如何为NSDateFormatter设置语言环境?我试过下面的代码,它不工作。NSDateFormatter语言环境

- (NSString *)localizedStringWithFormat:(NSString *)format { 

    NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
    [df setDateFormat:format]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: @"fr_FR"]; 
    cal.locale = locale; 
    df.calendar = cal; 
    return [df stringFromDate:self]; 
} 

请让我知道如何使这项工作。

谢谢。

+1

我只是直接设置日期格式的语言环境。我必须检查确定,但是您的方案可能会为currentCalendar的* every *用户设置语言环境。 (不明显,为什么它不会工作,否则。) –

+1

顺便说一下,是什么让你说它不工作? –

+0

将您的期望结果添加到您的问题将是很好的。或者你收到什么结果会让你觉得它不起作用。记住Xcode NSLog中显示的日期/时间是GMT。 –

回答

9
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *locale = [[NSLocale alloc] 
        initWithLocaleIdentifier:@"he"]; 
[dateFormatter setLocale:locale]; 
2

有点迟到了,但是这是我在斯威夫特今天的表现:

let df = NSDateFormatter() 
df.locale = NSLocale.currentLocale() 
df.timeStyle = .MediumStyle 
df.dateStyle = .MediumStyle 
println("Date: \(df.stringFromDate(obj.dateSent!))") 

根据您的操作系统区域设置,输出应该是这样的(我在德国):

Date: 27.11.2014 12:30:39 

注:就想通了很多人偶然发现这太问题,所以我想这不能伤害回答。

1

添加这个,因为我花了一些时间试图不使用我的日期格式化程序中的本地化区域设置。

来自apple文档: 当您不需要任何本地化时,请使用系统区域设置。使用当前的区域设置来格式化显示给用户的文本。

代码:[formatter setLocale:[NSLocale systemLocale]];

0

的情况下,会有人找斯威夫特3解决方案:

let dateFormatter = DateFormatter() 
let frLocale = Locale(identifier: "fr") 
dateFormatter.locale = frLocale