OGeek|极客世界-中国程序员成长平台

标题: ios - NSDateFormatter - setLocale 被忽略了吗? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:18
标题: ios - NSDateFormatter - setLocale 被忽略了吗?

我正在尝试解决一个臭名昭著的问题,即当用户将定位时间设置为 12 小时而不是默认的 24 小时时,NSDateFormatter 在不需要时返回“am/pm”日期(覆盖格式字符串)

阅读后,似乎最好的解决方案是将 dateFormatter 语言环境设置为 en_US_POSIX(我们将其用于 API 调用,因此需要忽略任何用户偏好)

但是,它似乎被忽略了?

我有一个分类如下:

@implementation NSDateFormatter (Locale)

- (id)initWithSafeLocale {
    static NSLocale* en_US_POSIX = nil;
    self = [self init];
    if (en_US_POSIX == nil) {
      en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier"en_US_POSIX"];
    }
    [self setLocale:en_US_POSIX];
    return self;    
}

@end

然后我打电话:

sharedInstance.dateFormatter = [[NSDateFormatter alloc] initWithSafeLocale];
[sharedInstance.dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];

但是,日期仍然打印为

2015-09-28 11:00:00 pm +0000

我做错了什么似乎忽略了 setLocale?

引用:What is the best way to deal with the NSDateFormatter locale "feechur"?



Best Answer-推荐答案


问题只是您如何使用 NSLog() 打印日期。这将调用 [NSDate description],它将使用用户的默认语言环境。

来自 docs (descriptionWithLocale):

If you pass nil, NSDate formats the date in the same way as the description property.

On OS X v10.4 and earlier, this parameter was an NSDictionary object. If you pass in an NSDictionary object on OS X v10.5, NSDate uses the default user locale—the same as if you passed in [NSLocale currentLocale].

您应该使用日期格式化程序来打印格式化的字符串。

关于ios - NSDateFormatter - setLocale 被忽略了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737588/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4