NSDateFormatter区域设置
如何为NSDateFormatter设置Locale? 我已经尝试了下面的代码,它不起作用。
- (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]; }
请让我知道如何使这项工作。
谢谢。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"he"]; [dateFormatter setLocale:locale];
派对有点晚了,但这就是我今天在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
注意:只是想到更多的人偶然发现了这个问题,所以我想回答这个问题并不容易。
添加这个,因为我花了一些时间试图不在我的日期格式化程序中使用本地化的区域设置。
来自apple docs: 当您不想要任何本地化时,请使用系统区域设置。 使用当前区域设置来格式化显示给用户的文本。
代码:[formatter setLocale:[NSLocale systemLocale]];
万一有人会寻找Swift 3解决方案:
let dateFormatter = DateFormatter() let frLocale = Locale(identifier: "fr") dateFormatter.locale = frLocale