7

如何为 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];
}

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

谢谢。

4

4 回答 4

15
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] 
                     initWithLocaleIdentifier:@"he"];
[dateFormatter setLocale:locale];
于 2013-09-23T20:15:28.223 回答
5

如果有人会寻找Swift 3解决方案:

let dateFormatter = DateFormatter()
let frLocale = Locale(identifier: "fr")
dateFormatter.locale = frLocale
于 2017-02-01T01:32:32.897 回答
3

聚会有点晚了,但这就是我今天在 Swift 中所做的:

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

注意:刚刚发现有更多的人偶然发现了这个 SO 问题,所以我想回答一下也无妨。

于 2014-11-27T23:09:47.727 回答
2

添加这个是因为我花了一些时间尝试不在我的日期格式化程序中使用本地化的语言环境。

来自苹果文档:当您不想要任何本地化时使用系统语言环境。使用当前语言环境来格式化您向用户显示的文本。

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

于 2016-02-05T16:30:53.603 回答