4

我正在尝试从 nsdate 对象获取本地化的工作日

+ (NSString *)localizedWeekdayForDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
    dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:[NSLocale localeWithLocaleIdentifier:language]];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    return formattedDateString;
}

语言字符串总是“en”......即使你的设备语言不是英语......我试过 [NSLocale currentLocale]; 以及preferedLanguages ...这也不起作用..

有什么建议么?

4

2 回答 2

6
[NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:[NSLocale localeWithLocaleIdentifier:language]]

不设置语言环境,它只返回一个NSString. 语言环境需要设置为:

- (void)setLocale:(NSLocale *)locale

例子:

客观C

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"fr"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"EEEE"];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"formattedDateString: '%@'", formattedDateString);

NSLog 输出:

格式化日期字符串:'狂欢'

斯威夫特 3

let date = Date()
let dateFormatter = DateFormatter()
let locale = Locale(identifier:"fr")
dateFormatter.locale = locale
dateFormatter.dateFormat = "EEEE"
let formattedDateString = dateFormatter.string(from:date)
print("formattedDateString: \(formattedDateString)")

输出:

格式化日期字符串:'狂欢'

于 2013-12-31T13:50:54.080 回答
0

您忘记设置 dateFormatter 的本地:

+ (NSString *)localizedWeekdayForDate:(NSDate *)date
{
    NSLocale *currentLocale = [NSLocale currentLocale];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = currentLocale;
    dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:currentLocale];

    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    return formattedDateString;
}
于 2013-12-31T13:43:25.807 回答