在iOs应用程序中从NSDate本地化的工作日

时间:2013-12-31 13:36:34

标签: ios nsdateformatter nslocale

我正在尝试从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];以及偏好的语言......这也行不通..

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

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

不设置区域设置,只返回NSString。区域设置需要设置为:

- (void)setLocale:(NSLocale *)locale

示例:

的ObjectiveC

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输出:

  

formattedDateString:'mardi'

Swift 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)")

输出:

  

formattedDateString:'mardi'

答案 1 :(得分: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;
}