【问题标题】:Localized weekday from NSDate in iOs app来自 iOS 应用中 NSDate 的本地化工作日
【发布时间】:2013-12-31 13:36:34
【问题描述】:

我正在尝试从 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...这也行不通..

有什么建议吗?

【问题讨论】:

  • 我认为您将语言与区域设置混淆了。像这样将语言环境绑定到设备语言是一个坏主意。例如;我的设备设置为英语,但我的区域格式(区域设置)是土耳其语。使用您的代码,我将始终使用美国日期格式。
  • 正确...我现在使用的是regons格式

标签: ios nsdateformatter nslocale


【解决方案1】:
[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 输出:

formattedDateString: '狂欢'

斯威夫特 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: '狂欢'

【讨论】:

  • 使用dateFormatter.dateFormat 将正确设置日期格式。
  • 好的。注意 OP 的 `dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:currentLocale];'没有按照 OP 的预期设置语言环境。我写的不好,我会改的。在你的行中
【解决方案2】:

您忘记设置 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2014-08-18
    • 2016-12-12
    相关资源
    最近更新 更多